<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 4.2.0">
  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/blog/images/logo.svg" color="#222">

<link rel="stylesheet" href="/blog/css/main.css">


<link rel="stylesheet" href="/blog/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"dttx123.gitee.io","root":"/blog/","scheme":"Gemini","version":"8.0.0-rc.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},"path":"search.xml"};
  </script>

  <meta name="description" content="IT">
<meta property="og:type" content="website">
<meta property="og:title" content="Starry Night">
<meta property="og:url" content="http://dttx123.gitee.io/page/2/index.html">
<meta property="og:site_name" content="Starry Night">
<meta property="og:description" content="IT">
<meta property="og:locale" content="zh_CN">
<meta property="article:author" content="大春哥">
<meta name="twitter:card" content="summary">

<link rel="canonical" href="http://dttx123.gitee.io/page/2/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : true,
    isPost : false,
    lang   : 'zh-CN'
  };
</script>

  <title>Starry Night</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏">
        <span class="toggle-line toggle-line-first"></span>
        <span class="toggle-line toggle-line-middle"></span>
        <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/blog/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">Starry Night</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
      <p class="site-subtitle" itemprop="description">这就朕为你打下的江山</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/blog/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/blog/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/blog/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/blog/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/blog/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a>

  </li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup">
        <div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div id="search-result">
  <div id="no-result">
    <i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>
  </div>
</div>

    </div>
  </div>

</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content index posts-expand">
            
      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://dttx123.gitee.io/2018/08/01/nodejs/04-mysq/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
      <meta itemprop="name" content="大春哥">
      <meta itemprop="description" content="IT">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Starry Night">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blog/2018/08/01/nodejs/04-mysq/" class="post-title-link" itemprop="url">sql 基础</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2018-08-01 00:00:00" itemprop="dateCreated datePublished" datetime="2018-08-01T00:00:00+08:00">2018-08-01</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-05-13 11:35:51" itemprop="dateModified" datetime="2020-05-13T11:35:51+08:00">2020-05-13</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/%E6%95%B0%E6%8D%AE%E5%BA%93/" itemprop="url" rel="index"><span itemprop="name">数据库</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="基本概念"><a href="#基本概念" class="headerlink" title="基本概念"></a>基本概念</h1><h2 id="为什么要有数据库"><a href="#为什么要有数据库" class="headerlink" title="为什么要有数据库"></a>为什么要有数据库</h2><p>没有数据库，我们的数据都是存储在文件当中的，那么文件存储数据的缺点有：</p>
<ul>
<li>文件的安全性问题。</li>
<li>文件不利于查询和对数据的管理。</li>
<li>文件不利于存放海量数据</li>
<li>文件在程序中控制不方便</li>
</ul>
<h2 id="什么是数据库"><a href="#什么是数据库" class="headerlink" title="什么是数据库"></a>什么是数据库</h2><p>数据库，简而言之可视为电子化的文件柜——存储电子文件的处所，用户可以对文件中的数据运行增加、删除、修改、查询等操作。</p>
<p>前端程序员只需要对数据库有一定了解即可。</p>
<p><strong>浏览器—-&gt;服务器—-&gt;数据库</strong></p>
<h2 id="数据库的分类"><a href="#数据库的分类" class="headerlink" title="数据库的分类"></a>数据库的分类</h2><p>关系型数据库：</p>
<ul>
<li><strong>MySQL</strong>、</li>
<li>Oracle、</li>
<li>SQL Server</li>
<li>SQLite（安卓）</li>
</ul>
<p>非关系型数据库</p>
<ul>
<li>mongodb</li>
<li>redis</li>
<li>BigTable</li>
</ul>
<p>DBA</p>
<h2 id="数据库中基本术语"><a href="#数据库中基本术语" class="headerlink" title="数据库中基本术语"></a>数据库中基本术语</h2><ul>
<li>数据库<code>database</code>：存放数据的仓库，一般一个项目中的数据会存储到一个数据库中</li>
<li>表<code>table</code>： 一个表对应一类数据，比如学生表，老师表</li>
<li>列<code>columns</code>:一张表由多列组成，也叫一个字段，比如学生的姓名，成绩，年龄等</li>
<li>行<code>rows</code>: 一个学生信息对应一行，一行也叫一条记录。</li>
</ul>
<h1 id="数据库的可视化操作"><a href="#数据库的可视化操作" class="headerlink" title="数据库的可视化操作"></a>数据库的可视化操作</h1><h2 id="创建数据库"><a href="#创建数据库" class="headerlink" title="创建数据库"></a>创建数据库</h2><h2 id="创建表"><a href="#创建表" class="headerlink" title="创建表"></a>创建表</h2><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">存储以下学生信息</span><br><span class="line"></span><br><span class="line">&#123;id: 1, name: &#39;张三&#39;, age: 18, gender: &#39;男&#39;, content: &#39;这是描述信息‘&#125;</span><br></pre></td></tr></table></figure>



<h2 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h2><p><code>int</code>: 整数类型</p>
<p><code>varchar</code>: 字符类型</p>
<p><code>datetime</code>: 日期类型</p>
<h1 id="数据库的常见命令"><a href="#数据库的常见命令" class="headerlink" title="数据库的常见命令"></a>数据库的常见命令</h1><blockquote>
<p>SQL: 结构化查询语言(Structured Query Language)简称SQL  。用于数据库的增删改查以及管理等功能。</p>
</blockquote>
<h2 id="数据库相关"><a href="#数据库相关" class="headerlink" title="数据库相关"></a>数据库相关</h2><ul>
<li><p><code>--</code>SQL中的注释</p>
</li>
<li><p><code>SHOW DATABASES;</code> 查看所有的数据</p>
</li>
<li><p><code>CREATE DATABASE mydb;</code> 创建数据库</p>
</li>
<li><p><code>DROP DATABASE mydb;</code>删除数据库</p>
</li>
<li><p><code>USE mydb;</code> 使用数据库</p>
</li>
</ul>
<h2 id="表相关"><a href="#表相关" class="headerlink" title="表相关"></a>表相关</h2><ul>
<li><code>SHOW TABLES;</code>查看当前数据库中所有的表</li>
<li>创建表</li>
</ul>
<figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">CREATE</span> <span class="keyword">TABLE</span> <span class="keyword">user</span>(</span><br><span class="line">	<span class="keyword">id</span> <span class="built_in">INT</span> auto_increment PRIMARY <span class="keyword">KEY</span>,</span><br><span class="line">	<span class="keyword">name</span> <span class="built_in">VARCHAR</span>(<span class="number">255</span>) <span class="keyword">NOT</span> <span class="literal">NULL</span>,</span><br><span class="line">	age <span class="built_in">INT</span> ,</span><br><span class="line">	gender <span class="built_in">VARCHAR</span>(<span class="number">4</span>),</span><br><span class="line">	<span class="keyword">content</span> <span class="built_in">VARCHAR</span>(<span class="number">255</span>)</span><br><span class="line">)</span><br></pre></td></tr></table></figure>

<ul>
<li><code>DROP TABLE user;</code>删除表</li>
</ul>
<h2 id="插入数据"><a href="#插入数据" class="headerlink" title="插入数据"></a>插入数据</h2><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> <span class="keyword">user</span> (<span class="keyword">name</span>, age, gender, <span class="keyword">content</span>) <span class="keyword">VALUES</span> (<span class="string">'胡聪聪'</span>, <span class="number">18</span>, <span class="string">'男'</span>, <span class="string">'哈哈哈，哈哈哈'</span>)</span><br><span class="line"><span class="comment">-- 如果省略列名，那么必须要和字段一一对应</span></span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> <span class="keyword">user</span> <span class="keyword">VALUES</span> (<span class="literal">null</span>, <span class="string">'胡聪聪'</span>, <span class="number">18</span>, <span class="string">'男'</span>, <span class="string">'哈哈哈，哈哈哈'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">INSERT</span> <span class="keyword">INTO</span> <span class="keyword">user</span> <span class="keyword">SET</span> <span class="keyword">name</span>=<span class="string">'hcc'</span>, age=<span class="number">18</span>, gender=<span class="string">'男'</span>, <span class="keyword">content</span>=<span class="string">'嘻嘻嘻'</span></span><br></pre></td></tr></table></figure>

<h2 id="修改数据"><a href="#修改数据" class="headerlink" title="修改数据"></a>修改数据</h2><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">// 修改所有的数据</span><br><span class="line"><span class="keyword">UPDATE</span> <span class="keyword">USER</span> <span class="keyword">SET</span> <span class="keyword">name</span>=<span class="string">'胡西西'</span></span><br><span class="line">// 根据条件修改</span><br><span class="line"><span class="keyword">UPDATE</span> <span class="keyword">USER</span> <span class="keyword">set</span> <span class="keyword">name</span>=<span class="string">'胡聪聪'</span>, <span class="keyword">content</span>=<span class="string">"这是内容"</span> <span class="keyword">WHERE</span> <span class="keyword">id</span> = <span class="number">2</span></span><br></pre></td></tr></table></figure>



<h2 id="删除数据"><a href="#删除数据" class="headerlink" title="删除数据"></a>删除数据</h2><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">// 删除所有的数据</span><br><span class="line"><span class="keyword">DELETE</span> <span class="keyword">FROM</span> <span class="keyword">USER</span></span><br><span class="line"></span><br><span class="line">// 删除<span class="keyword">id</span>为<span class="number">5</span>的数据</span><br><span class="line"><span class="keyword">DELETE</span> <span class="keyword">FROM</span> <span class="keyword">USER</span> <span class="keyword">WHERE</span> <span class="keyword">id</span> = <span class="number">5</span></span><br></pre></td></tr></table></figure>



<h2 id="查询数据"><a href="#查询数据" class="headerlink" title="查询数据"></a>查询数据</h2><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">-- 查询所有数据</span></span><br><span class="line"><span class="keyword">SELECT</span> * <span class="keyword">FROM</span> <span class="keyword">user</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 查询指定列</span></span><br><span class="line"><span class="keyword">SELECT</span> <span class="keyword">id</span>, <span class="keyword">name</span>,age <span class="keyword">from</span> <span class="keyword">user</span></span><br></pre></td></tr></table></figure>



<h2 id="条件查询"><a href="#条件查询" class="headerlink" title="条件查询"></a>条件查询</h2><figure class="highlight sql"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">--- 并且</span></span><br><span class="line"><span class="keyword">SELECT</span> * <span class="keyword">from</span> <span class="keyword">user</span> <span class="keyword">where</span> <span class="keyword">name</span>=<span class="string">'胡聪聪'</span> <span class="keyword">AND</span> age=<span class="number">21</span></span><br><span class="line"></span><br><span class="line"><span class="comment">--- 或者</span></span><br><span class="line"><span class="keyword">SELECT</span> * <span class="keyword">from</span> <span class="keyword">user</span> <span class="keyword">where</span> <span class="keyword">name</span>=<span class="string">'胡聪聪'</span> <span class="keyword">or</span> age=<span class="number">21</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 范围查询</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- 模糊查询  %表示通配  _表示单个字符</span></span><br><span class="line"><span class="keyword">SELECT</span> * <span class="keyword">from</span> <span class="keyword">user</span> <span class="keyword">where</span> <span class="keyword">name</span> <span class="keyword">LIKE</span> <span class="string">'胡%'</span></span><br><span class="line"></span><br><span class="line"><span class="comment">-- in语句</span></span><br><span class="line"><span class="keyword">SELECT</span> * <span class="keyword">from</span> <span class="keyword">user</span> <span class="keyword">where</span> <span class="keyword">name</span> <span class="keyword">in</span> (<span class="string">'胡聪聪'</span>, <span class="string">'hcc'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">-- order by</span></span><br><span class="line"><span class="comment">-- 排序需要写在最后面，，asc升序  desc：降序</span></span><br><span class="line"><span class="keyword">SELECT</span> * <span class="keyword">from</span> <span class="keyword">user</span> <span class="keyword">ORDER</span> <span class="keyword">BY</span> <span class="keyword">id</span> <span class="keyword">desc</span></span><br></pre></td></tr></table></figure>



<h2 id="导入和导出数据库脚本"><a href="#导入和导出数据库脚本" class="headerlink" title="导入和导出数据库脚本"></a>导入和导出数据库脚本</h2><h1 id="node操作mysql"><a href="#node操作mysql" class="headerlink" title="node操作mysql"></a>node操作mysql</h1><h2 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h2><ul>
<li>安装</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install mysql</span><br></pre></td></tr></table></figure>

<ul>
<li>基本使用</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 导入第三方包</span></span><br><span class="line"><span class="keyword">const</span> mysql = <span class="built_in">require</span>(<span class="string">'mysql'</span>)</span><br><span class="line"><span class="comment">// 创建连接</span></span><br><span class="line"><span class="keyword">var</span> connection = mysql.createConnection(&#123;</span><br><span class="line">  <span class="comment">// 本地</span></span><br><span class="line">  host: <span class="string">'localhost'</span>,</span><br><span class="line">  user: <span class="string">'root'</span>,</span><br><span class="line">  password: <span class="string">'root'</span>,</span><br><span class="line">  <span class="comment">// 数据库名称</span></span><br><span class="line">  database: <span class="string">'mydb'</span>,</span><br><span class="line">  port: <span class="number">3306</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 连接数据库</span></span><br><span class="line">connection.connect()</span><br><span class="line"></span><br><span class="line"><span class="comment">// 执行sql语句</span></span><br><span class="line">connection.query(<span class="string">'select * from user where id = 8'</span>, (err, result) =&gt; &#123;</span><br><span class="line">  <span class="keyword">if</span> (err) <span class="keyword">return</span> <span class="built_in">console</span>.log(<span class="string">'查询失败'</span>, err)</span><br><span class="line">  <span class="comment">// result返回的是数组， 数组中是一个对象</span></span><br><span class="line">  <span class="built_in">console</span>.log(result)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 关闭连接</span></span><br><span class="line">connection.end()</span><br></pre></td></tr></table></figure>



<h2 id="查询语句"><a href="#查询语句" class="headerlink" title="查询语句"></a>查询语句</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> name = <span class="string">'胡聪聪'</span></span><br><span class="line"><span class="comment">// 使用?表示占位，</span></span><br><span class="line">connect.query(<span class="string">`select * from user where name=?`</span>, name, (err, result) =&gt; &#123;</span><br><span class="line">  <span class="keyword">if</span> (err) <span class="keyword">return</span> <span class="built_in">console</span>.log(<span class="string">'错误了'</span>, err)</span><br><span class="line">  <span class="built_in">console</span>.log(result)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>



<h2 id="插入语句"><a href="#插入语句" class="headerlink" title="插入语句"></a>插入语句</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">connect.query(</span><br><span class="line">  <span class="string">'insert into user (name, age, gender, content) values (?, ?, ?, ?)'</span>,</span><br><span class="line">  [<span class="string">'胡嘻嘻'</span>, <span class="number">18</span>, <span class="string">'男'</span>, <span class="string">'哈哈哈哈'</span>],</span><br><span class="line">  err =&gt; &#123;</span><br><span class="line">    <span class="keyword">if</span> (err) <span class="keyword">return</span> <span class="built_in">console</span>.log(<span class="string">'错误'</span>, err)</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'添加成功了'</span>)</span><br><span class="line">  &#125;</span><br><span class="line">)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 方式2</span></span><br><span class="line">connect.query(</span><br><span class="line">  <span class="string">'insert into user values ?'</span>,</span><br><span class="line">  &#123;</span><br><span class="line">    name: <span class="string">'胡洗洗'</span>,</span><br><span class="line">    age: <span class="number">30</span>,</span><br><span class="line">    gender: <span class="string">'男'</span>,</span><br><span class="line">    content: <span class="string">'哈哈哈'</span></span><br><span class="line">  &#125;,</span><br><span class="line">  (err, result) =&gt; &#123;</span><br><span class="line">    <span class="keyword">if</span> (err) <span class="keyword">return</span> <span class="built_in">console</span>.log(<span class="string">'错误'</span>, err)</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'添加成功了'</span>, result)</span><br><span class="line">  &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>



<h2 id="修改语句"><a href="#修改语句" class="headerlink" title="修改语句"></a>修改语句</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">connect.query(</span><br><span class="line">  <span class="string">'update user set ? where id = ?'</span>,</span><br><span class="line">  [</span><br><span class="line">    &#123;</span><br><span class="line">      name: <span class="string">'胡洗洗'</span>,</span><br><span class="line">      age: <span class="number">30</span>,</span><br><span class="line">      gender: <span class="string">'男'</span>,</span><br><span class="line">      content: <span class="string">'哈哈哈'</span></span><br><span class="line">    &#125;,</span><br><span class="line">    <span class="number">10</span></span><br><span class="line">  ],</span><br><span class="line">  (err, result) =&gt; &#123;</span><br><span class="line">    <span class="keyword">if</span> (err) <span class="keyword">return</span> <span class="built_in">console</span>.log(<span class="string">'错误'</span>, err)</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'添加成功了'</span>, result)</span><br><span class="line">  &#125;</span><br><span class="line">)</span><br></pre></td></tr></table></figure>



<h2 id="删除语句"><a href="#删除语句" class="headerlink" title="删除语句"></a>删除语句</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">connect.query(<span class="string">'delete from user where id = ?'</span>, [<span class="number">10</span>], (err, result) =&gt; &#123;</span><br><span class="line">  <span class="keyword">if</span> (err) <span class="keyword">return</span> <span class="built_in">console</span>.log(<span class="string">'失败'</span>, err)</span><br><span class="line">  <span class="built_in">console</span>.log(result)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>





<h2 id="db模块封装"><a href="#db模块封装" class="headerlink" title="db模块封装"></a>db模块封装</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> mysql = <span class="built_in">require</span>(<span class="string">'mysql'</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 配置相关数据</span></span><br><span class="line"><span class="keyword">var</span> config = &#123;</span><br><span class="line">  host: <span class="string">'127.0.0.1'</span>,</span><br><span class="line">  user: <span class="string">'root'</span>,</span><br><span class="line">  password: <span class="string">'root'</span>,</span><br><span class="line">  database: <span class="string">'ztest'</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">module</span>.exports.myQuery = <span class="function"><span class="keyword">function</span> (<span class="params">sql, param, fn</span>) </span>&#123;</span><br><span class="line">  <span class="comment">// 1- 创建连接</span></span><br><span class="line">  <span class="keyword">const</span> con = mysql.createConnection(config);</span><br><span class="line">  <span class="comment">// 2- 连接</span></span><br><span class="line">  con.connect();</span><br><span class="line">  <span class="comment">// 3- 操作 </span></span><br><span class="line">  con.query(sql, param, (err, data) =&gt; &#123;</span><br><span class="line">    <span class="keyword">if</span> (err) &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="built_in">console</span>.log(err);</span><br><span class="line">    &#125;</span><br><span class="line">    fn &amp;&amp; fn(data);</span><br><span class="line">  &#125;)</span><br><span class="line">  <span class="comment">// 4- 断开</span></span><br><span class="line">  con.end();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://dttx123.gitee.io/2018/07/07/nodejs/03-express%E7%AC%94%E8%AE%B0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
      <meta itemprop="name" content="大春哥">
      <meta itemprop="description" content="IT">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Starry Night">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blog/2018/07/07/nodejs/03-express%E7%AC%94%E8%AE%B0/" class="post-title-link" itemprop="url">express</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2018-07-07 00:00:00" itemprop="dateCreated datePublished" datetime="2018-07-07T00:00:00+08:00">2018-07-07</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-05-13 11:34:47" itemprop="dateModified" datetime="2020-05-13T11:34:47+08:00">2020-05-13</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/node/" itemprop="url" rel="index"><span itemprop="name">node</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="Express"><a href="#Express" class="headerlink" title="Express"></a>Express</h1><h2 id="Express-框架"><a href="#Express-框架" class="headerlink" title="Express 框架"></a>Express 框架</h2><ul>
<li><strong>基于 Node.js 平台，快速、开放、极简的 web 开发框架</strong></li>
<li><a href="http://expressjs.com/" target="_blank" rel="noopener">express 官网</a></li>
<li><a href="http://expressjs.com.cn/" target="_blank" rel="noopener">express 中文网</a></li>
</ul>
<h3 id="起步"><a href="#起步" class="headerlink" title="起步"></a>起步</h3><ul>
<li>安装：<code>npm i express</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 导入 express</span></span><br><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">'express'</span>)</span><br><span class="line"><span class="comment">// 创建 express实例，也就是创建 express服务器</span></span><br><span class="line"><span class="keyword">var</span> app = express()</span><br><span class="line"></span><br><span class="line"><span class="comment">// 路由</span></span><br><span class="line">app.get(<span class="string">'/'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">  res.send(<span class="string">'Hello World!'</span>)</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 启动服务器</span></span><br><span class="line">app.listen(<span class="number">3000</span>, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'服务器已启动'</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h3 id="API说明"><a href="#API说明" class="headerlink" title="API说明"></a>API说明</h3><ul>
<li><code>express()</code>：创建一个Express应用，并返回，即：app</li>
<li><code>app.get()</code>：注册一个GET类型的路由<ul>
<li>注意：只要注册了路由，所有的请求都会被处理（未配置的请求路径，响应404）</li>
</ul>
</li>
<li><code>res.send()</code>：发送数据给客户端，并自动设置Content-Type<ul>
<li>参数可以是：字符串、数组、对象、Buffer</li>
<li>注意：只能使用一次</li>
</ul>
</li>
<li><code>req</code> 和 <code>res</code>：与http模块中的作用相同，是扩展后的请求和响应对象</li>
</ul>
<h2 id="注册路由"><a href="#注册路由" class="headerlink" title="注册路由"></a>注册路由</h2><ul>
<li>1 <code>app.METHOD</code>：比如：app.get / app.post / app.delete / app.patch</li>
<li>3 <code>app.use(path, callback)</code> 更重要的作用是处理中间件<ul>
<li>注意：只要是以path开头的请求地址，都可以被use处理</li>
<li>注意：可以处理任意的请求类型</li>
<li>注意：path参数可省略，默认值为：<code>/</code></li>
</ul>
</li>
</ul>
<h2 id="实现静态服务器"><a href="#实现静态服务器" class="headerlink" title="实现静态服务器"></a>实现静态服务器</h2><ul>
<li><code>req.path</code>：请求路径<ul>
<li>示例：URL为’example.com/users?sort=desc’，path表示：<code>/users</code></li>
</ul>
</li>
<li><code>res.sendFile()</code></li>
</ul>
<h3 id="处理静态资源"><a href="#处理静态资源" class="headerlink" title="处理静态资源"></a>处理静态资源</h3><ul>
<li>静态资源：图片、CSS、JavaScript 文件 等</li>
<li>如何处理？使用 express.static() 方法来托管静态资源</li>
<li>注意：<code>express.static()</code>可以调用多次</li>
<li>思考：<code>app.use(&#39;/web&#39;, express.static(&#39;web&#39;))</code> 的含义？<ul>
<li>访问：<code>http://localhost:3000/web/anoceanofsky.jpg</code></li>
</ul>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 托管web目录下的静态资源</span></span><br><span class="line">app.use(express.static(<span class="string">'web'</span>))</span><br><span class="line"><span class="comment">// 相当于：app.use('/', express.static('web'))</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 访问上述静态资源</span></span><br><span class="line"><span class="comment">// http://localhost:3000/anoceanofsky.jpg</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 当请求达到服务器后，express就会到web目录下，查找anoceanofsky.jpg</span></span><br><span class="line"><span class="comment">// 并读取该文件，返回给浏览器</span></span><br></pre></td></tr></table></figure>

<h2 id="request常用属性和方法"><a href="#request常用属性和方法" class="headerlink" title="request常用属性和方法"></a>request常用属性和方法</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取请求路基中的参数，是一个对象 ---&gt; Get请求参数</span></span><br><span class="line">req.query</span><br><span class="line"></span><br><span class="line"><span class="comment">// 获取POST请求参数，需要配置`body-parser`模块， POST请求参数</span></span><br><span class="line">req.body</span><br></pre></td></tr></table></figure>

<ul>
<li>获取<code>POST</code>请求参数</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 导入body-parser模块</span></span><br><span class="line"><span class="keyword">var</span> bodyParser = <span class="built_in">require</span>(<span class="string">'body-parser'</span>);</span><br><span class="line"><span class="comment">// 将POST请求参数转化为对象，存储到req.body中</span></span><br><span class="line">app.use(bodyParser.urlencoded(&#123; <span class="attr">extended</span>: <span class="literal">true</span> &#125;)); <span class="comment">// for parsing application/x-www-form-urlencoded</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 此时，就可以获取到POST请求参数了</span></span><br><span class="line"><span class="built_in">console</span>.log(req.body)</span><br></pre></td></tr></table></figure>

<h2 id="response常用属性和方法"><a href="#response常用属性和方法" class="headerlink" title="response常用属性和方法"></a>response常用属性和方法</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// send() 发送数据给客户端，并自动设置Content-Type</span></span><br><span class="line">res.send()</span><br><span class="line"></span><br><span class="line"><span class="comment">// 发送文件给浏览器，并根据文件后缀名自动设置Content-Type</span></span><br><span class="line"><span class="comment">// 注意：文件路径必须是绝对路径</span></span><br><span class="line">res.sendFile(path.join(__dirname, <span class="string">'index.html'</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment">// 设置HTTP响应码</span></span><br><span class="line">res.status(<span class="number">200</span>)</span><br><span class="line"><span class="comment">// 设置响应头</span></span><br><span class="line">res.set(<span class="string">'Content-Type'</span>, <span class="string">'text/plain'</span>)</span><br><span class="line">res.set(&#123;</span><br><span class="line">  <span class="string">'Content-Type'</span>: <span class="string">'text/plain'</span>,</span><br><span class="line">  <span class="string">'cute'</span>: <span class="string">'fangfang'</span></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 重定向</span></span><br><span class="line">res.redirect(<span class="string">'/index'</span>)</span><br></pre></td></tr></table></figure>

<h2 id="Express使用模板引擎"><a href="#Express使用模板引擎" class="headerlink" title="Express使用模板引擎"></a>Express使用模板引擎</h2><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 为后缀为html的模板设置模板引擎</span></span><br><span class="line">app.engine(<span class="string">'html'</span>, <span class="built_in">require</span>(<span class="string">'express-art-template'</span>))</span><br><span class="line"></span><br><span class="line"><span class="comment">// 设置模板文件所在的目录</span></span><br><span class="line">app.set(<span class="string">'views'</span>, <span class="string">'./'</span>)</span><br><span class="line"><span class="comment">// 设置模板文件的后缀为 html</span></span><br><span class="line">app.set(<span class="string">'view engine'</span>, <span class="string">'html'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 渲染 index.html 模板文件，并发送给浏览器</span></span><br><span class="line">res.render(<span class="string">'index'</span>, &#123; <span class="attr">list</span>: [] &#125;)</span><br></pre></td></tr></table></figure>

<h2 id="Express-中外置路由使用"><a href="#Express-中外置路由使用" class="headerlink" title="Express 中外置路由使用"></a>Express 中外置路由使用</h2><ul>
<li>目的：将路由封装到一个独立的路由模块中，有利于代码的封装和模块化</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">  router.js 文件代码如下:</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 1 加载 express 模块</span></span><br><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">'express'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 2 调用 express.Router() 方法，得到一个路由容器实例</span></span><br><span class="line"><span class="keyword">var</span> router = express.Router()</span><br><span class="line"></span><br><span class="line"><span class="comment">// 3 为 router 添加不同的路由</span></span><br><span class="line">router.get(<span class="string">'/'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">  res.send(<span class="string">'hello express'</span>)</span><br><span class="line">&#125;)</span><br><span class="line">router.get(<span class="string">'/add'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">req, res</span>) </span>&#123;</span><br><span class="line"></span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 4. 将 router 路由容器导出</span></span><br><span class="line"><span class="built_in">module</span>.exports = router</span><br></pre></td></tr></table></figure>

<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/*</span></span><br><span class="line"><span class="comment">  在 app.js 文件中：</span></span><br><span class="line"><span class="comment">*/</span></span><br><span class="line"><span class="keyword">var</span> express = <span class="built_in">require</span>(<span class="string">'express'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 1 加载上面自定义的路由模块</span></span><br><span class="line"><span class="keyword">var</span> router = <span class="built_in">require</span>(<span class="string">'./router'</span>)</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> app = express()</span><br><span class="line"></span><br><span class="line"><span class="comment">// 2. 将自定义路由模块 router 通过 app.use() 方法挂载到 app 实例上</span></span><br><span class="line"><span class="comment">//    这样 app 实例程序就拥有了 router 的路由</span></span><br><span class="line">app.use( router )</span><br><span class="line"></span><br><span class="line">app.listen(<span class="number">3000</span>, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">'running...'</span>)</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="中间件"><a href="#中间件" class="headerlink" title="中间件"></a>中间件</h2><p><em>中间件（Middleware）</em> 是一个函数，它可以访问请求对象<code>req</code>, 响应对象<code>res</code>, 可以通过<code>next</code>参数将中间件传递给下一个中间件</p>
<p>中间件作用： 给req 和 res 拓展功能 </p>
<p>中间件的功能包括：</p>
<ul>
<li>执行任何代码。</li>
<li>修改请求和响应对象。</li>
<li>终结请求-响应循环。</li>
<li>调用堆栈中的下一个中间件。</li>
</ul>
<p>定义一个中间件</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//添加一个中间件</span></span><br><span class="line"><span class="comment">//中间件是啥：中间件就是一个函数，中间件可以访问到req和res，可以通过next发送给下一个中间件</span></span><br><span class="line">app.use(<span class="function"><span class="keyword">function</span>(<span class="params">req,res, next</span>) </span>&#123;</span><br><span class="line">  req.aa = <span class="string">"大春哥"</span>;</span><br><span class="line">  res.bb = <span class="string">"很帅"</span>;</span><br><span class="line">  <span class="comment">//中间件可以通过next传递给下一个中间件</span></span><br><span class="line">  next();</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h2 id="body-parser中间件的使用"><a href="#body-parser中间件的使用" class="headerlink" title="body-parser中间件的使用"></a>body-parser中间件的使用</h2><ul>
<li>获取get请求的参数：<code>req.query</code></li>
<li>获取post请求的参数<code>req.body</code>，但是需要借助<code>body-parser</code>中间件</li>
</ul>
<p>安装：</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install body-parser</span><br></pre></td></tr></table></figure>

<p>使用</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1. 导入body-parser中间件</span></span><br><span class="line"><span class="keyword">var</span> bodyParser = <span class="built_in">require</span>(<span class="string">'body-parser'</span>);</span><br><span class="line"><span class="comment">//使用body-parser中间件</span></span><br><span class="line"><span class="comment">//extended:true 表示使用qs库来解析查询字符串  extended：false表示使用querystring库来解析字符串</span></span><br><span class="line">app.use(bodyParser.urlencoded(&#123;<span class="attr">extended</span>:<span class="literal">false</span>&#125;));</span><br><span class="line"></span><br><span class="line"><span class="comment">//3. 通过req.body获取参数</span></span><br><span class="line">app.post(<span class="string">"/"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(req.body);</span><br><span class="line">  res.send(<span class="string">"哈哈"</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p><strong>注意：中间件是有执行顺序的</strong></p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://dttx123.gitee.io/2018/06/07/nodejs/02-%E6%A8%A1%E5%9D%97%E5%8C%96%E7%AC%94%E8%AE%B0/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
      <meta itemprop="name" content="大春哥">
      <meta itemprop="description" content="IT">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Starry Night">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blog/2018/06/07/nodejs/02-%E6%A8%A1%E5%9D%97%E5%8C%96%E7%AC%94%E8%AE%B0/" class="post-title-link" itemprop="url">模块化</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2018-06-07 00:00:00" itemprop="dateCreated datePublished" datetime="2018-06-07T00:00:00+08:00">2018-06-07</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-05-13 11:33:26" itemprop="dateModified" datetime="2020-05-13T11:33:26+08:00">2020-05-13</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/node/" itemprop="url" rel="index"><span itemprop="name">node</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="模块化"><a href="#模块化" class="headerlink" title="模块化"></a>模块化</h1><h2 id="基本概念"><a href="#基本概念" class="headerlink" title="基本概念"></a>基本概念</h2><blockquote>
<p>在nodejs中，应用由模块组成，nodejs中采用commonJS模块规范。</p>
</blockquote>
<ol>
<li>一个js文件就是一个模块</li>
<li>每个模块都是一个独立的作用域，在这个而文件中定义的变量、函数、对象都是私有的，对其他文件不可见。</li>
</ol>
<ul>
<li><code>01-模块化的概念</code>用于演示每一个模块都有自己单独的作用域</li>
</ul>
<h2 id="node中模块分类"><a href="#node中模块分类" class="headerlink" title="node中模块分类"></a>node中模块分类</h2><ul>
<li>1 核心模块<ul>
<li>由 node 本身提供，不需要单独安装（npm），可直接引入使用</li>
</ul>
</li>
<li>2 第三方模块<ul>
<li>由社区或个人提供，需要通过npm安装后使用</li>
</ul>
</li>
<li>3 自定义模块<ul>
<li>由我们自己创建，比如：tool.js 、 user.js</li>
</ul>
</li>
</ul>
<h3 id="核心模块"><a href="#核心模块" class="headerlink" title="核心模块"></a>核心模块</h3><ul>
<li>fs：文件操作模块</li>
<li>http：网络操作模块</li>
<li>path：路径操作模块</li>
<li>url: 解析地址的模块</li>
<li>querystring: 解析参数字符串的模块</li>
<li>基本使用：1 先引入  2 再使用</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 引入模块</span></span><br><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">'fs'</span>);</span><br></pre></td></tr></table></figure>

<h3 id="第三方模块"><a href="#第三方模块" class="headerlink" title="第三方模块"></a>第三方模块</h3><ul>
<li>第三方模块是由 社区或个人 提供的</li>
<li>比如：mime模块/art-template/jquery…</li>
<li>基本使用：1 先通过npm下载 2 再引入 3 最后使用</li>
</ul>
<h3 id="用户自定义模块"><a href="#用户自定义模块" class="headerlink" title="用户自定义模块"></a>用户自定义模块</h3><ul>
<li>由开发人员创建的模块（JS文件）</li>
<li>基本使用：1 创建模块 2 引入模块</li>
<li>注意：自定义模块的路径必须以<code>./</code>获取<code>../</code>开头</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 加载模块</span></span><br><span class="line"><span class="built_in">require</span>(<span class="string">'./a'</span>)     <span class="comment">// 推荐使用，省略.js后缀！</span></span><br><span class="line"></span><br><span class="line"><span class="built_in">require</span>(<span class="string">'./a.js'</span>)</span><br></pre></td></tr></table></figure>

<h2 id="模块的导入与导出"><a href="#模块的导入与导出" class="headerlink" title="模块的导入与导出"></a>模块的导入与导出</h2><h3 id="模块导入"><a href="#模块导入" class="headerlink" title="模块导入"></a>模块导入</h3><ul>
<li>通过<code>require(&quot;fs&quot;)</code>来加载模块</li>
<li>如果是第三方模块，需要先使用npm进行下载</li>
<li>如果是自定义模块，需要加上相对路径<code>./</code>或者<code>../</code>,可以省略<code>.js</code>后缀，如果文件名是<code>index.js</code>那么index.js也可以省略。</li>
<li>模块可以被多次引入，但是只会在第一次加载</li>
</ul>
<h3 id="模块导出"><a href="#模块导出" class="headerlink" title="模块导出"></a>模块导出</h3><ul>
<li>在模块的内部，<code>module</code>变量代表的就是当前模块，它的<code>exports</code>属性就是对外的接口，加载某个模块，加载的就是<code>module.exports</code>属性，这个属性指向一个空的对象。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//module.exports指向的是一个对象，我们给对象增加属性即可。</span></span><br><span class="line"><span class="comment">//module.exports.num = 123;</span></span><br><span class="line"><span class="comment">//module.exports.age = 18;</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//通过module.exports也可以导出一个值，但是多次导出会覆盖</span></span><br><span class="line"><span class="built_in">module</span>.exports = <span class="string">'123'</span>;</span><br><span class="line"><span class="built_in">module</span>.exports = <span class="string">"abc"</span>;</span><br></pre></td></tr></table></figure>



<h3 id="module-exports与exports"><a href="#module-exports与exports" class="headerlink" title="module.exports与exports"></a>module.exports与exports</h3><ul>
<li><code>exports</code> 是 <code>module.exports</code> 的引用</li>
<li>注意：给 <code>module.exports</code> 赋值会切断与 <code>exports</code> 之间的联系<ul>
<li>1 直接添加属性两者皆可</li>
<li>2 赋值操作时，只能使用 <code>module.exports</code></li>
</ul>
</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>.log( <span class="built_in">module</span>.exports === exports ) <span class="comment">// ==&gt; true</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 等价操作</span></span><br><span class="line"><span class="built_in">module</span>.exports.num = <span class="number">123</span></span><br><span class="line">exports.num = <span class="number">123</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// 赋值操作：不要使用 exports = &#123;&#125;</span></span><br><span class="line"><span class="built_in">module</span>.exports = &#123;&#125;</span><br></pre></td></tr></table></figure>

<h3 id="第三方模块（以mime包为例）"><a href="#第三方模块（以mime包为例）" class="headerlink" title="第三方模块（以mime包为例）"></a>第三方模块（以mime包为例）</h3><ul>
<li>先基于当前文件模块所属目录找 node_modules 目录</li>
<li>如果找到，则去该目录中找 mime 目录</li>
<li>如果找到 mime 目录，则找该目录中的 package.json 文件</li>
<li>如果找到 package.json 文件，则找该文件中的 main 属性</li>
<li>如果找到 main 属性，则拿到该属性对应的文件路径</li>
<li>如果找到 mime 目录之后<ul>
<li>发现没有 package.json</li>
<li>或者 有 package.json 没有 main 属性</li>
<li>或者 有 main 属性，但是指向的路径不存在</li>
<li>则 node 会默认去看一下 mime 目录中有没有 index.js index.node index.json 文件</li>
</ul>
</li>
<li>如果找不到 index 或者找不到 mime 或者找不到 node_modules</li>
<li>则进入上一级目录找 node_moudles 查找规则同上</li>
<li>如果上一级还找不到，继续向上，一直到当前文件所属磁盘根目录</li>
<li>如果最后到磁盘根目录还找不到，最后报错：<code>can not find module xxx</code></li>
</ul>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://dttx123.gitee.io/2018/05/05/nodejs/01-nodeJs%E5%9F%BA%E7%A1%80/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
      <meta itemprop="name" content="大春哥">
      <meta itemprop="description" content="IT">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Starry Night">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blog/2018/05/05/nodejs/01-nodeJs%E5%9F%BA%E7%A1%80/" class="post-title-link" itemprop="url">node基础</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2018-05-05 00:00:00" itemprop="dateCreated datePublished" datetime="2018-05-05T00:00:00+08:00">2018-05-05</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-05-13 11:35:06" itemprop="dateModified" datetime="2020-05-13T11:35:06+08:00">2020-05-13</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/node/" itemprop="url" rel="index"><span itemprop="name">node</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="nodejs基本介绍"><a href="#nodejs基本介绍" class="headerlink" title="nodejs基本介绍"></a>nodejs基本介绍</h1><h2 id="为什么要学习nodejs"><a href="#为什么要学习nodejs" class="headerlink" title="为什么要学习nodejs"></a>为什么要学习nodejs</h2><p>为什么要学习服务端的开发？</p>
<ol>
<li>通过学习Node.js开发理解<strong>服务器开发</strong>、<strong>Web请求和响应过程</strong>、 <strong>了解服务器端如何与客户端配合</strong></li>
<li>作为前端开发工程师（FE）需要具备一定的服务端开发能力</li>
</ol>
<p>服务器端开发语言有很多，为什么要选择nodejs</p>
<ol>
<li>降低编程语言切换的成本(nodejs实质上用的还是javascript)</li>
<li>NodeJS是前端项目的基础设施，前端项目中用到的大量工具 (大前端)  webpack  less-css</li>
<li><strong>对于前端工程师，面试时对于nodejs有一定的要求</strong></li>
</ol>
<ul>
<li><a href="https://www.zhipin.com/job_detail/d35a590c832162ed1XB42Ny-Flo~.html?ka=search_list_7" target="_blank" rel="noopener">web前端10-20k</a></li>
</ul>
<h2 id="node-js-是什么？"><a href="#node-js-是什么？" class="headerlink" title="node.js 是什么？"></a>node.js 是什么？</h2><p>node.js，也叫作node，或者nodejs，指的都是一个东西。</p>
<ol>
<li><a href="https://nodejs.org/" target="_blank" rel="noopener">node.js官方网站</a></li>
<li><a href="http://nodejs.cn/" target="_blank" rel="noopener">node.js中文网</a></li>
<li><a href="https://cnodejs.org/" target="_blank" rel="noopener">node.js 中文社区</a></li>
</ol>
<p>Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境，nodejs允许javascript代码运行在服务端</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">1. nodejs不是一门新的编程语言，nodejs是在服务端运行javascript的运行环境</span><br><span class="line">2. 运行环境：写得程序想要运行必须要有对应的运行环境</span><br><span class="line">	php代码必须要有apache服务器</span><br><span class="line">	在web端，浏览器就是javascript的运行环境</span><br><span class="line">	在node端，nodejs就是javascript的运行环境</span><br><span class="line">2. javascript并不只是能运行在浏览器端，浏览器端能够运行js是因为浏览器有js解析器，因此只需要有js解析器，任何软件都可以运行js。</span><br><span class="line">3. nodejs可以在服务端运行js，因为nodejs是基于chrome v8的js引擎。</span><br></pre></td></tr></table></figure>

<p><strong>nodejs的本质：不是一门新的编程语言，nodejs是javascript运行在服务端的运行环境，编程语言还是javascript</strong></p>
<h2 id="nodejs与浏览器的区别"><a href="#nodejs与浏览器的区别" class="headerlink" title="nodejs与浏览器的区别"></a>nodejs与浏览器的区别</h2><p>相同点：nodejs与浏览器都是javascript的运行环境，都能够解析js程序。对于ECMAScript语法来说，在nodejs和浏览器中都能运行。</p>
<p>不同点：nodejs无法使用DOM和BOM的操作，浏览器无法执行nodejs中的文件操作等功能</p>
<p>思考：</p>
<ol>
<li>在浏览器端，可以使用javascript操作数据库么？</li>
<li>在nodejs端，可以使用BOM和DOM的方法么？</li>
<li>我们学习nodejs，学习什么内容？ </li>
</ol>
<h2 id="nodejs可以干什么？"><a href="#nodejs可以干什么？" class="headerlink" title="nodejs可以干什么？"></a>nodejs可以干什么？</h2><ol>
<li>开发服务端程序</li>
<li>开发命令行工具（CLI），比如npm,webpack,gulp,less,sass等 vue-cli</li>
<li>开发桌面应用程序（借助 node-webkit、electron 等框架实现）</li>
</ol>
<h1 id="安装nodejs"><a href="#安装nodejs" class="headerlink" title="安装nodejs"></a>安装nodejs</h1><h2 id="nodejs版本"><a href="#nodejs版本" class="headerlink" title="nodejs版本"></a>nodejs版本</h2><p>下载地址</p>
<ul>
<li><a href="https://nodejs.org/en/download/" target="_blank" rel="noopener">当前版本</a></li>
<li><a href="https://nodejs.org/en/download/releases/" target="_blank" rel="noopener">历史版本</a></li>
</ul>
<p>官网术语解释</p>
<ul>
<li>LTS 版本：Long-term Support 版本，长期支持版，即稳定版。</li>
<li>Current 版本：Latest Features 版本，最新版本，新特性会在该版本中最先加入。</li>
</ul>
<p>查看node版本</p>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">node -v</span><br></pre></td></tr></table></figure>

<h1 id="运行nodejs程序"><a href="#运行nodejs程序" class="headerlink" title="运行nodejs程序"></a>运行nodejs程序</h1><ul>
<li>创建js文件 <code>helloworld.js</code></li>
<li>写nodejs的内容：<code>console.log(&#39;hello nodejs&#39;)</code></li>
<li>打开命令窗口 <code>cmd</code><ul>
<li>shift加右键打开命令窗口，执行 <code>node 文件名.js</code>即可</li>
<li>给vscode安装<code>terminal</code>插件，直接在vscode中执行</li>
</ul>
</li>
<li>执行命令：<code>node helloworld.js</code></li>
</ul>
<p>注意：在nodejs中是无法使用DOM和BOM的内容的，因此<code>document, window</code>等内容是无法使用的。</p>
<h1 id="global模块-全局变量"><a href="#global模块-全局变量" class="headerlink" title="global模块-全局变量"></a>global模块-全局变量</h1><blockquote>
<p>Node.js 中的全局对象是 <code>global</code>, 类似于浏览器中的<code>window</code></p>
</blockquote>
<p>常用的global属性</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">console</span>: 用于打印日志</span><br><span class="line">setTimeout/clearTimeout: 设置清除延时器</span><br><span class="line">setInterval/clearInterval: 设置清除定时器</span><br><span class="line"></span><br><span class="line">__dirname: 当前文件的路径，不包括文件名</span><br><span class="line">__filename： 获取当前文件的路径，包括文件名</span><br><span class="line"></span><br><span class="line"><span class="comment">//与模块化相关的，模块化的时候会用到</span></span><br><span class="line"><span class="built_in">require</span></span><br><span class="line">exports</span><br><span class="line"><span class="built_in">module</span></span><br></pre></td></tr></table></figure>

<h1 id="fs模块"><a href="#fs模块" class="headerlink" title="fs模块"></a>fs模块</h1><blockquote>
<p>fs模块是nodejs中最常用的一个模块，因此掌握fs模块非常的有必要，fs模块的方法非常多,用到了哪个查哪个即可。</p>
<p>文档地址：<a href="http://nodejs.cn/api/fs.html" target="_blank" rel="noopener">http://nodejs.cn/api/fs.html</a></p>
</blockquote>
<p>  在nodejs中，提供了fs模块，这是node的核心模块</p>
<p>  注意：</p>
<ol>
<li>除了global模块中的内容可以直接使用，其他模块都是需要加载的。</li>
<li>fs模块不是全局的，不能直接使用。因此需要导入才能使用。</li>
</ol>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">"fs"</span>);</span><br></pre></td></tr></table></figure>

<h2 id="读取文件"><a href="#读取文件" class="headerlink" title="读取文件"></a>读取文件</h2><blockquote>
<p>语法：fs.readFile(path[, options], callback)</p>
</blockquote>
<p>方式一：不传编码参数</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//参数1： 文件的名字</span></span><br><span class="line"><span class="comment">//参数2： 读取文件的回调函数</span></span><br><span class="line">  <span class="comment">//参数1：错误对象，如果读取失败，err会包含错误信息，如果读取成功，err是null</span></span><br><span class="line">  <span class="comment">//参数2：读取成功后的数据（是一个Buffer对象）</span></span><br><span class="line">fs.readFile(<span class="string">"data.txt"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err, data</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(err);</span><br><span class="line">  <span class="built_in">console</span>.log(data);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>方式二：传编码参数</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//参数1： 文件的路径</span></span><br><span class="line"><span class="comment">//参数2： 编码，如果设置了，返回一个字符串，如果没有设置，会返回一个buffer对象</span></span><br><span class="line"><span class="comment">//参数3： 回调函数</span></span><br><span class="line">fs.readFile(<span class="string">"data.txt"</span>, <span class="string">"utf8"</span>,<span class="function"><span class="keyword">function</span>(<span class="params">err, data</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(err);</span><br><span class="line">  <span class="built_in">console</span>.log(data);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>关于Buffer对象</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> Buffer对象是Nodejs用于处理二进制数据的。</span><br><span class="line"><span class="number">2.</span> 其实任意的数据在计算机底层都是二进制数据，因为计算机只认识二进制。</span><br><span class="line"><span class="number">3.</span> 所以读取任意的文件，返回的结果都是二进制数据，即Buffer对象</span><br><span class="line"><span class="number">4.</span> Buffer对象可以调用toString()方法转换成字符串。</span><br></pre></td></tr></table></figure>

<h2 id="写文件"><a href="#写文件" class="headerlink" title="写文件"></a>写文件</h2><blockquote>
<p>语法：fs.writeFile(file, data[, options], callback)</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//参数1：写入的文件名(如果文件不存在，会自动创建)</span></span><br><span class="line"><span class="comment">//参数2：写入的文件内容（注意：写入的内容会覆盖以前的内容）</span></span><br><span class="line"><span class="comment">//参数3：写文件后的回调函数</span></span><br><span class="line">fs.writeFile(<span class="string">"2.txt"</span>, <span class="string">"hello world, 我是一个中国人"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(err) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">console</span>.log(<span class="string">"写入文件失败"</span>, err);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"写入文件成功"</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>注意：</p>
<ol>
<li>写文件的时候，会把原来的内容给覆盖掉</li>
</ol>
<h2 id="追加文件"><a href="#追加文件" class="headerlink" title="追加文件"></a>追加文件</h2><blockquote>
<p>语法：fs.appendFile(path, data[, options], callback)</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//参数1：追加的文件名(如果文件不存在，会自动创建)</span></span><br><span class="line"><span class="comment">//参数2：追加的文件内容（注意：写入的内容会覆盖以前的内容）</span></span><br><span class="line"><span class="comment">//参数3：追加文件后的回调函数</span></span><br><span class="line">fs.appendFile(<span class="string">"2.txt"</span>, <span class="string">"我是追加的内容"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(err) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">console</span>.log(<span class="string">"追加文件内容失败"</span>);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"追加文件内容成功"</span>);</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<p>思考：如果没有appendFile，通过readFile与writeFile应该怎么实现？</p>
<h2 id="文件同步与异步的说明"><a href="#文件同步与异步的说明" class="headerlink" title="文件同步与异步的说明"></a>文件同步与异步的说明</h2><blockquote>
<p>fs中所有的文件操作，都提供了异步和同步两种方式</p>
</blockquote>
<p>异步方式：不会阻塞代码的执行</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//异步方式</span></span><br><span class="line"><span class="keyword">var</span> fs = <span class="built_in">require</span>(<span class="string">"fs"</span>);</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(<span class="number">111</span>);</span><br><span class="line">fs.readFile(<span class="string">"2.txt"</span>, <span class="string">"utf8"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err, data</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(err) &#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">console</span>.log(<span class="string">"读取文件失败"</span>, err);</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="built_in">console</span>.log(data);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="string">"222"</span>);</span><br></pre></td></tr></table></figure>

<p>同步方式：会阻塞代码的执行</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//同步方式</span></span><br><span class="line"><span class="built_in">console</span>.log(<span class="number">111</span>);</span><br><span class="line"><span class="keyword">var</span> result = fs.readFileSync(<span class="string">"2.txt"</span>, <span class="string">"utf-8"</span>);</span><br><span class="line"><span class="built_in">console</span>.log(result);</span><br><span class="line"><span class="built_in">console</span>.log(<span class="number">222</span>);</span><br></pre></td></tr></table></figure>

<p>总结：同步操作使用虽然简单，但是会影响性能，因此尽量使用异步方法，尤其是在工作过程中。</p>
<h2 id="其他api（了解）"><a href="#其他api（了解）" class="headerlink" title="其他api（了解）"></a>其他api（了解）</h2><p>方法有很多，但是用起来都非常的简单，学会查文档</p>
<p>文档：<a href="http://nodejs.cn/api/fs.html" target="_blank" rel="noopener">http://nodejs.cn/api/fs.html</a></p>
<table>
<thead>
<tr>
<th>方法名</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td><code>fs.readFile(path, callback)</code></td>
<td>读取文件内容（异步）</td>
</tr>
<tr>
<td><code>fs.readFileSync(path)</code></td>
<td>读取文件内容（同步）</td>
</tr>
<tr>
<td><code>fs.writeFile(path, data, callback)</code></td>
<td>写入文件内容（异步）</td>
</tr>
<tr>
<td><code>fs.writeFileSync(path, data)</code></td>
<td>写入文件内容（同步）</td>
</tr>
<tr>
<td><code>fs.appendFile(path, data, callback)</code></td>
<td>追加文件内容（异步）</td>
</tr>
<tr>
<td><code>fs.appendFileSync(path, data)</code></td>
<td>追加文件内容（同步）</td>
</tr>
<tr>
<td><code>fs.rename(oldPath, newPath, callback)</code></td>
<td>重命名文件（异步）</td>
</tr>
<tr>
<td><code>fs.renameSync(oldPath, newPath)</code></td>
<td>重命名文件（同步）</td>
</tr>
<tr>
<td><code>fs.unlink(path, callback)</code></td>
<td>删除文件（异步）</td>
</tr>
<tr>
<td><code>fs.unlinkSync(path)</code></td>
<td>删除文件（同步）</td>
</tr>
<tr>
<td><code>fs.mkdir(path, mode, callback)</code></td>
<td>创建文件夹（异步）</td>
</tr>
<tr>
<td><code>fs.mkdirSync(path, mode)</code></td>
<td>创建文件夹（同步）</td>
</tr>
<tr>
<td><code>fs.rmdir(path, callback)</code></td>
<td>删除文件夹（异步）</td>
</tr>
<tr>
<td><code>fs.rmdirSync(path)</code></td>
<td>删除文件夹（同步）</td>
</tr>
<tr>
<td><code>fs.readdir(path, option, callback)</code></td>
<td>读取文件夹内容（异步）</td>
</tr>
<tr>
<td><code>fs.readdirSync(path, option)</code></td>
<td>读取文件夹内容（同步）</td>
</tr>
<tr>
<td><code>fs.stat(path, callback)</code></td>
<td>查看文件状态（异步）</td>
</tr>
<tr>
<td><code>fs.statSync(path)</code></td>
<td>查看文件状态（同步）</td>
</tr>
</tbody></table>
<h1 id="path模块"><a href="#path模块" class="headerlink" title="path模块"></a>path模块</h1><h2 id="路径操作的问题"><a href="#路径操作的问题" class="headerlink" title="路径操作的问题"></a>路径操作的问题</h2><p>在读写文件的时候，文件路径可以写相对路径或者绝对路径</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//data.txt是相对路径，读取当前目录下的data.txt, 相对路径相对的是指向node命令的路径</span></span><br><span class="line"><span class="comment">//如果node命令不是在当前目录下执行就会报错， 在当前执行node命令的目录下查找data.txt，找不到</span></span><br><span class="line">fs.readFile(<span class="string">"data.txt"</span>, <span class="string">"utf8"</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err, data</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">if</span>(err) &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"读取文件失败"</span>, err);</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="built_in">console</span>.log(data);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>相对路径：相对于执行node命令的路径</p>
<p>绝对路径：<code>__dirname</code>: 当前文件的目录，<code>__filename</code>: 当前文件的目录，包含文件名</p>
<h2 id="path模块的常用方法"><a href="#path模块的常用方法" class="headerlink" title="path模块的常用方法"></a>path模块的常用方法</h2><blockquote>
<p>关于路径，在linux系统中，路径分隔符使用的是<code>/</code>，但是在windows系统中，路径使用的<code>\</code></p>
</blockquote>
<p>在我们拼写路径的时候会带来很多的麻烦，经常会出现windows下写的代码，在linux操作系统下执行不了，path模块就是为了解决这个问题而存在的。</p>
<p>常用方法：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">path.join();<span class="comment">//拼接路径</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//windows系统下</span></span><br><span class="line">&gt; path.join(<span class="string">"abc"</span>,<span class="string">"def"</span>,<span class="string">"gg"</span>, <span class="string">"index.html"</span>)</span><br><span class="line"><span class="string">"abc\def\gg\a.html"</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//linux系统下</span></span><br><span class="line">&gt; path.join(<span class="string">"abc"</span>,<span class="string">"def"</span>,<span class="string">"gg"</span>, <span class="string">"index.html"</span>)</span><br><span class="line"><span class="string">'abc/def/gg/index.html'</span></span><br><span class="line"></span><br><span class="line">path.basename(path[, ext])	返回文件的最后一部分</span><br><span class="line">path.dirname(path)	返回路径的目录名</span><br><span class="line">path.extname(path)	获取路径的扩展名</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> path = <span class="built_in">require</span>(<span class="string">"path"</span>);</span><br><span class="line"><span class="keyword">var</span> temp = <span class="string">"abc\\def\\gg\\a.html"</span>;</span><br><span class="line"><span class="built_in">console</span>.log(path.basename(temp));<span class="comment">//a.html</span></span><br><span class="line"><span class="built_in">console</span>.log(path.dirname(temp));<span class="comment">//abc\def\gg</span></span><br><span class="line"><span class="built_in">console</span>.log(path.extname(temp));<span class="comment">//.html</span></span><br></pre></td></tr></table></figure>

<p>【优化读写文件的代码】</p>
<h2 id="path模块其他api（了解）"><a href="#path模块其他api（了解）" class="headerlink" title="path模块其他api（了解）"></a>path模块其他api（了解）</h2><table>
<thead>
<tr>
<th>方法名</th>
<th>描述</th>
</tr>
</thead>
<tbody><tr>
<td><code>path.basename(path[, ext])</code></td>
<td>返回文件的最后一部分</td>
</tr>
<tr>
<td><code>path.dirname(path)</code></td>
<td>返回路径的目录名</td>
</tr>
<tr>
<td><code>path.extname(path)</code></td>
<td>获取路径的扩展名</td>
</tr>
<tr>
<td><code>path.isAbsolute(path)</code></td>
<td>判断目录是否是绝对路径</td>
</tr>
<tr>
<td><code>path.join([...paths])</code></td>
<td>将所有的path片段拼接成一个规范的路径</td>
</tr>
<tr>
<td><code>path.normalize(path)</code></td>
<td>规范化路径</td>
</tr>
<tr>
<td><code>path.parse(path)</code></td>
<td>将一个路径解析成一个path对象</td>
</tr>
<tr>
<td><code>path.format(pathObj)</code></td>
<td>讲一个path对象解析成一个规范的路径</td>
</tr>
</tbody></table>
<h1 id="http模块"><a href="#http模块" class="headerlink" title="http模块"></a>http模块</h1><p>复习：</p>
<p>​    1- 输入网址浏览器的请求过程</p>
<p>​    2- http协议的构成</p>
<h2 id="创建服务器基本步骤"><a href="#创建服务器基本步骤" class="headerlink" title="创建服务器基本步骤"></a>创建服务器基本步骤</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1. 导入http模块，http模块是node的核心模块，作用是用来创建http服务器的。</span></span><br><span class="line"><span class="keyword">var</span> http = <span class="built_in">require</span>(<span class="string">"http"</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//2. 创建服务器</span></span><br><span class="line"><span class="keyword">var</span> server = http.createServer();</span><br><span class="line"></span><br><span class="line"><span class="comment">//3. 服务器处理请求</span></span><br><span class="line">server.on(<span class="string">"request"</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"我接收到请求了"</span>);</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">//4. 启动服务器，监听某个端口</span></span><br><span class="line">server.listen(<span class="number">9999</span>, <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(<span class="string">"服务器启动成功了, 请访问： http://localhost:9999"</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>详细说明</p>
<ol>
<li>给服务器注册request事件，只要服务器接收到了客户端的请求，就会触发request事件</li>
<li>request事件有两个参数，request表示请求对象，可以获取所有与请求相关的信息，response是响应对象，可以设置所有与响应相关的信息。</li>
<li>服务器监听的端口范围为：1-65535之间，推荐使用3000以上的端口，因为3000以下的端口一般留给系统使用</li>
</ol>
<h2 id="request对象详解"><a href="#request对象详解" class="headerlink" title="request对象详解"></a>request对象详解</h2><p>文档地址：<a href="http://nodejs.cn/api/http.html#http_message_headers" target="_blank" rel="noopener">http://nodejs.cn/api/http.html#http_message_headers</a></p>
<p>常见属性：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">headers: 所有的请求头信息</span><br><span class="line">method： 请求的方式</span><br><span class="line">url： 请求的地址</span><br></pre></td></tr></table></figure>

<p>注意：在发送请求的时候，可能会出现两次请求的情况，这是因为谷歌浏览器会自动增加一个<code>favicon.ico</code>的请求。</p>
<p>小结：request对象中，常用的就是method和url两个参数</p>
<h2 id="response对象详解"><a href="#response对象详解" class="headerlink" title="response对象详解"></a>response对象详解</h2><p>文档地址：<a href="http://nodejs.cn/api/http.html#http_class_http_serverresponse" target="_blank" rel="noopener">http://nodejs.cn/api/http.html#http_class_http_serverresponse</a></p>
<p>常见的属性和方法：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">res.write(data): 给浏览器发送请求体，可以调用多次，从而提供连续的请求体</span><br><span class="line">res.end();   通知服务器，所有响应头和响应主体都已被发送，即服务器将其视为已完成。</span><br><span class="line">res.end(data); 结束请求，并且响应一段内容，相当于res.write(data) + res.end()</span><br><span class="line">res.statusCode: 响应的的状态码 <span class="number">200</span> <span class="number">404</span> <span class="number">500</span></span><br><span class="line">res.statusMessage: 响应的状态信息， OK Not Found ,会根据statusCode自动设置。</span><br><span class="line">res.setHeader(name, value); 设置响应头信息， 比如content-type</span><br><span class="line">res.writeHead(statusCode, statusMessage, options); 设置响应头，同时可以设置状态码和状态信息。</span><br></pre></td></tr></table></figure>

<p><strong>注意：必须先设置响应头，才能设置响应。</strong> </p>
<h1 id="实现静态WEB服务器"><a href="#实现静态WEB服务器" class="headerlink" title="实现静态WEB服务器"></a>实现静态WEB服务器</h1><h2 id="服务器响应首页"><a href="#服务器响应首页" class="headerlink" title="服务器响应首页"></a>服务器响应首页</h2><ul>
<li>注意：浏览器中输入的URL地址，仅仅是一个标识，不与服务器中的目录一致。也就是说：返回什么内容是由服务端的逻辑决定</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">server.on(<span class="string">'request'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">req, res</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> url = req.url</span><br><span class="line">  <span class="keyword">if</span>(url === <span class="string">'/'</span>) &#123;</span><br><span class="line">    fs.readFile(<span class="string">'./index.html'</span>, <span class="function"><span class="keyword">function</span>(<span class="params">err, data</span>) </span>&#123;</span><br><span class="line">      <span class="keyword">if</span>(err) &#123;</span><br><span class="line">        <span class="keyword">return</span> res.end(<span class="string">'您访问的资源不存在~'</span>)</span><br><span class="line">      &#125;</span><br><span class="line"></span><br><span class="line">      res.end(data)</span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="根据根据不同url，响应不同文件"><a href="#根据根据不同url，响应不同文件" class="headerlink" title="根据根据不同url，响应不同文件"></a>根据根据不同url，响应不同文件</h2><h2 id="content-type设置-MIME类型"><a href="#content-type设置-MIME类型" class="headerlink" title="content-type设置-MIME类型"></a>content-type设置-MIME类型</h2><ul>
<li>MIME(Multipurpose Internet Mail Extensions)多用途Internet邮件扩展类型 是一种表示文档性质和格式的标准化方式</li>
<li>浏览器通常使用MIME类型（而不是文件扩展名）来确定如何处理文档；因此服务器将正确的MIME类型附加到响应对象的头部是非常重要的</li>
<li><a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Basics_of_HTTP/MIME_Types" target="_blank" rel="noopener">MIME 类型</a></li>
</ul>
<h2 id="静态资源的通用处理"><a href="#静态资源的通用处理" class="headerlink" title="静态资源的通用处理"></a>静态资源的通用处理</h2><h2 id="MIME类型的通用处理-mime模块"><a href="#MIME类型的通用处理-mime模块" class="headerlink" title="MIME类型的通用处理-mime模块"></a>MIME类型的通用处理-mime模块</h2><ul>
<li>作用：获取文件的MIME类型</li>
<li>安装：<code>npm i mime</code></li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> mime = <span class="built_in">require</span>(<span class="string">'mime'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 获取路径对应的MIME类型</span></span><br><span class="line">mime.getType(<span class="string">'txt'</span>)                    <span class="comment">// ⇨ 'text/plain'</span></span><br><span class="line"><span class="comment">// 根据MIME获取到文件后缀名</span></span><br><span class="line">mime.getExtension(<span class="string">'text/plain'</span>)        <span class="comment">// ⇨ 'txt'</span></span><br></pre></td></tr></table></figure>

<h1 id="npm-Node包管理工具"><a href="#npm-Node包管理工具" class="headerlink" title="npm - Node包管理工具"></a>npm - Node包管理工具</h1><h2 id="npm的基本概念"><a href="#npm的基本概念" class="headerlink" title="npm的基本概念"></a>npm的基本概念</h2><ul>
<li>node package manager</li>
<li><a href="https://npmjs.com" target="_blank" rel="noopener">npm官网</a></li>
<li><a href="https://www.npmjs.com.cn/" target="_blank" rel="noopener">npm中文文档</a></li>
</ul>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">1. npm 是node的包管理工具，</span><br><span class="line">2. 它是世界上最大的软件注册表，每星期大约有 30 亿次的下载量，包含超过 600000 个 包（package） （即，代码模块）。</span><br><span class="line">3. 来自各大洲的开源软件开发者使用 npm 互相分享和借鉴。包的结构使您能够轻松跟踪依赖项和版本。</span><br></pre></td></tr></table></figure>

<ul>
<li>作用：通过<code>npm</code>来快速安装开发中使用的包</li>
<li>npm不需要安装，只要安装了node，就自带了<code>npm</code></li>
</ul>
<h2 id="npm基本使用"><a href="#npm基本使用" class="headerlink" title="npm基本使用"></a>npm基本使用</h2><h3 id="初始化包"><a href="#初始化包" class="headerlink" title="初始化包"></a>初始化包</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">npm init;    <span class="comment">//这个命令用于初始化一个包，创建一个package.json文件，我们的项目都应该先执行npm init</span></span><br><span class="line">npm init -y;  <span class="comment">//快速的初始化一个包， 不能是一个中文名</span></span><br></pre></td></tr></table></figure>

<h3 id="安装包"><a href="#安装包" class="headerlink" title="安装包"></a>安装包</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">npm install 包名;  <span class="comment">//安装指定的包名的最新版本到项目中</span></span><br><span class="line">npm install 包名@版本号;  <span class="comment">//安装指定包的指定版本</span></span><br><span class="line"></span><br><span class="line">npm i 包名； <span class="comment">//简写</span></span><br></pre></td></tr></table></figure>

<h3 id="卸载包"><a href="#卸载包" class="headerlink" title="卸载包"></a>卸载包</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm uninstall 包名;  <span class="comment">//卸载已经安装的包</span></span><br></pre></td></tr></table></figure>

<h3 id="清除缓存"><a href="#清除缓存" class="headerlink" title="清除缓存"></a>清除缓存</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm cache clean -f <span class="comment">// 如果npm安装失败了，可以用这个命令来清除缓存</span></span><br></pre></td></tr></table></figure>

<h2 id="package-json文件"><a href="#package-json文件" class="headerlink" title="package.json文件"></a>package.json文件</h2><p>package.json文件，包（项目）描述文件，用来管理组织一个包（项目），它是一个纯JSON格式的。</p>
<ul>
<li>作用：描述当前项目（包）的信息，描述当前包（项目）的依赖项</li>
<li>如何生成：<code>npm init</code>或者<code>npm init -y</code></li>
<li>作用<ul>
<li>作为一个标准的包，必须要有<code>package.json</code>文件进行描述</li>
<li>一个项目的node_modules目录通常都会很大，不用拷贝node_modules目录，可以通过package.json文件配合<code>npm install</code>直接安装项目所有的依赖项</li>
</ul>
</li>
<li>描述内容</li>
</ul>
<figure class="highlight json"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="attr">"name"</span>: <span class="string">"03-npm"</span>,  <span class="comment">//描述了包的名字，不能有中文</span></span><br><span class="line">  <span class="attr">"version"</span>: <span class="string">"1.0.0"</span>,  <span class="comment">//描述了包的的版本信息， x.y.z  如果只是修复bug，需要更新Z位。如果是新增了功能，但是向下兼容，需要更新Y位。如果有大变动，向下不兼容，需要更新X位。</span></span><br><span class="line">  <span class="attr">"description"</span>: <span class="string">""</span>, <span class="comment">//包的描述信息</span></span><br><span class="line">  <span class="attr">"main"</span>: <span class="string">"index.js"</span>, <span class="comment">//入口文件（模块化加载规则的时候详细的讲）</span></span><br><span class="line">  <span class="attr">"scripts"</span>: &#123;  <span class="comment">//配置一些脚本，在vue的时候会用到，现在体会不到</span></span><br><span class="line">    <span class="attr">"test"</span>: <span class="string">"echo \"Error: no test specified\" &amp;&amp; exit 1"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  <span class="attr">"keywords"</span>: [],  <span class="comment">//关键字（方便搜索）</span></span><br><span class="line">  <span class="attr">"author"</span>: <span class="string">""</span>,  <span class="comment">//作者的信息</span></span><br><span class="line">  <span class="attr">"license"</span>: <span class="string">"ISC"</span>,  <span class="comment">//许可证，开源协议</span></span><br><span class="line">  <span class="attr">"dependencies"</span>: &#123;   <span class="comment">//重要，项目的依赖， 方便代码的共享  通过 npm install可以直接安装所有的依赖项</span></span><br><span class="line">    <span class="attr">"bootstrap"</span>: <span class="string">"^3.3.7"</span>,</span><br><span class="line">    <span class="attr">"jquery"</span>: <span class="string">"^3.3.1"</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>注意：一个合法的package.json，必须要有name和version两个属性</strong> </p>
<h2 id="本地安装和全局安装"><a href="#本地安装和全局安装" class="headerlink" title="本地安装和全局安装"></a>本地安装和全局安装</h2><p>有两种方式用来安装 npm 包：本地安装和全局安装。选用哪种方式来安装，取决于你如何使用这个包。 </p>
<ul>
<li>全局安装：如果你想将其作为一个命令行工具，那么你应该将其安装到全局。这种安装方式后可以让你在任何目录下使用这个命令。比如less命令，webpack命令，hcc-md命令 。</li>
<li>本地安装：如果你自己的模块依赖于某个包，并通过 Node.js 的 <code>require</code> 加载，那么你应该选择本地安装，这种方式也是 <code>npm install</code> 命令的默认行为。</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 全局安装,会把npm包安装到C:\Users\HUCC\AppData\Roaming\npm目录下，作为命令行工具使用</span></span><br><span class="line">npm install -g 包名;</span><br><span class="line"></span><br><span class="line"><span class="comment">//本地安装，会把npm包安装到当前项目的node_modules文件中，作为项目的依赖</span></span><br><span class="line">npm install 包名;</span><br></pre></td></tr></table></figure>

<h2 id="常见的命令行工具"><a href="#常见的命令行工具" class="headerlink" title="常见的命令行工具"></a>常见的命令行工具</h2><h3 id="nrm"><a href="#nrm" class="headerlink" title="nrm"></a>nrm</h3><ul>
<li>nrm：npm registry manager（npm仓库地址管理工具）</li>
<li>安装：<code>npm i -g nrm</code></li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#</span><span class="bash"> 带*表示当前正在使用的地址</span></span><br><span class="line"></span><br><span class="line"><span class="meta">#</span><span class="bash"> 查看仓库地址列表</span></span><br><span class="line">nrm ls</span><br><span class="line"></span><br><span class="line"><span class="meta">#</span><span class="bash"> 切换仓库地址</span></span><br><span class="line">nrm use taobao</span><br></pre></td></tr></table></figure>

<h3 id="nodemon-自动重启"><a href="#nodemon-自动重启" class="headerlink" title="nodemon 自动重启"></a>nodemon 自动重启</h3><ul>
<li>作用：监视到js文件修改后，自动重启node程序</li>
<li>安装：<code>npm i -g nodemon</code></li>
<li>使用：<code>nodemon app.js</code> 运行node程序</li>
</ul>
<h1 id="实现动态WEB服务器"><a href="#实现动态WEB服务器" class="headerlink" title="实现动态WEB服务器"></a>实现动态WEB服务器</h1><h2 id="在node中使用art-template"><a href="#在node中使用art-template" class="headerlink" title="在node中使用art-template"></a>在node中使用art-template</h2><ul>
<li><a href="https://aui.github.io/art-template/zh-cn/docs/" target="_blank" rel="noopener">文档</a></li>
<li>安装</li>
</ul>
<figure class="highlight bash"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install art-template</span><br></pre></td></tr></table></figure>

<ul>
<li>核心方法</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 基于模板路径渲染模板</span></span><br><span class="line"><span class="comment">//参数1：文件的路径</span></span><br><span class="line"><span class="comment">//参数2：数据</span></span><br><span class="line"><span class="comment">//返回值：返回渲染后的内容</span></span><br><span class="line"><span class="comment">// template(filename, data)</span></span><br><span class="line"><span class="keyword">let</span> html = template(path.join(__dirname, <span class="string">"pages"</span>, <span class="string">"index.html"</span>), &#123;<span class="attr">name</span>:<span class="string">"大吉大利，今晚吃鸡"</span>&#125;);</span><br></pre></td></tr></table></figure>

<p><strong>注意点：文件的路径必须是绝对路径</strong></p>
<h2 id="get请求处理-url模块"><a href="#get请求处理-url模块" class="headerlink" title="get请求处理-url模块"></a>get请求处理-url模块</h2><ul>
<li>说明：用于 URL 处理与解析</li>
<li>注意：通过url拿到的查询参数都是字符串格式</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 导入url模块</span></span><br><span class="line"><span class="keyword">var</span> url = <span class="built_in">require</span>(<span class="string">'url'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 解析 URL 字符串并返回一个 URL 对象</span></span><br><span class="line"><span class="comment">// 第一个参数：表示要解析的URL字符串</span></span><br><span class="line"><span class="comment">// 第二个参数：是否将query属性（查询参数）解析为一个对象，如果为：true，则query是一个对象</span></span><br><span class="line"><span class="keyword">var</span> ret = url.parse(<span class="string">'http://localhost:3000/details?id=1&amp;name=jack'</span>, <span class="literal">true</span>)</span><br><span class="line"><span class="built_in">console</span>.log(ret.query) <span class="comment">// &#123; id: '1', name: 'jack' &#125;</span></span><br></pre></td></tr></table></figure>

<h2 id="服务端重定向"><a href="#服务端重定向" class="headerlink" title="服务端重定向"></a>服务端重定向</h2><ul>
<li><a href="https://developer.mozilla.org/zh-CN/docs/Web/HTTP/Status" target="_blank" rel="noopener">HTTP 状态码说明</a></li>
<li><a href="http://shuai.be/archives/301-302-redirection/" target="_blank" rel="noopener">301 和 302</a></li>
<li>说明：服务端可以通过HTTP状态码让浏览器中的页面重定向</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">res.writeHead(<span class="number">302</span>, &#123;</span><br><span class="line">  <span class="string">'Location'</span>: <span class="string">'/'</span></span><br><span class="line">&#125;)</span><br><span class="line">res.end()</span><br></pre></td></tr></table></figure>

<h2 id="POST请求参数的处理"><a href="#POST请求参数的处理" class="headerlink" title="POST请求参数的处理"></a>POST请求参数的处理</h2><ul>
<li>说明：POST请求可以发送大量数据，没有大小限制</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 接受POST参数</span></span><br><span class="line"><span class="keyword">var</span> postData = []</span><br><span class="line"></span><br><span class="line"><span class="comment">// data事件：用来接受客户端发送过来的POST请求数据</span></span><br><span class="line"><span class="keyword">var</span> result = <span class="string">""</span>;</span><br><span class="line">req.on(<span class="string">'data'</span>, <span class="function"><span class="keyword">function</span> (<span class="params">chunk</span>) </span>&#123;</span><br><span class="line">  result += chunk;</span><br><span class="line">&#125;)</span><br><span class="line"></span><br><span class="line"><span class="comment">// end事件：当POST数据接收完毕时，触发</span></span><br><span class="line">req.on(<span class="string">'end'</span>, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">  cosnole.log(result); </span><br><span class="line">&#125;)</span><br></pre></td></tr></table></figure>

<h2 id="请求体处理-querystring模块"><a href="#请求体处理-querystring模块" class="headerlink" title="请求体处理-querystring模块"></a>请求体处理-querystring模块</h2><ul>
<li>用于解析与格式化 URL 查询字符串</li>
<li>注意：只在专门处理查询字符串时使用</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// foo=bar&amp;abc=xyz&amp;abc=123</span></span><br><span class="line"><span class="keyword">var</span> querystring = <span class="built_in">require</span>(<span class="string">'querystring'</span>)</span><br><span class="line"></span><br><span class="line"><span class="comment">// 将查询参数转化为对象</span></span><br><span class="line"><span class="comment">// 第一个参数: 要解析的 URL 查询字符串</span></span><br><span class="line">querystring.parse(<span class="string">'foo=bar&amp;abc=xyz'</span>) <span class="comment">// &#123; foo: 'bar', abc: 'xyz' &#125;</span></span><br></pre></td></tr></table></figure>


      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://dttx123.gitee.io/2018/04/09/ES6/ES601/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
      <meta itemprop="name" content="大春哥">
      <meta itemprop="description" content="IT">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Starry Night">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blog/2018/04/09/ES6/ES601/" class="post-title-link" itemprop="url">ES6基础</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2018-04-09 00:00:00" itemprop="dateCreated datePublished" datetime="2018-04-09T00:00:00+08:00">2018-04-09</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-05-13 12:55:24" itemprop="dateModified" datetime="2020-05-13T12:55:24+08:00">2020-05-13</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/ES6/" itemprop="url" rel="index"><span itemprop="name">ES6</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="ESMAScript6"><a href="#ESMAScript6" class="headerlink" title="ESMAScript6"></a>ESMAScript6</h1><blockquote>
<p>ECMAScript 6.0（以下简称 ES6）是 JavaScript 语言的下一代标准，已经在 2015 年 6 月正式发布了。它的目标，是使得 JavaScript 语言可以用来编写复杂的大型应用程序，成为企业级开发语言。</p>
</blockquote>
<p>我们从node开始，会大量用到ES6中的一些新语法，因此在学习node之前需要先学习一下es6中提供的新语法</p>
<h2 id="ECMAScript与Javascript的关系"><a href="#ECMAScript与Javascript的关系" class="headerlink" title="ECMAScript与Javascript的关系"></a>ECMAScript与Javascript的关系</h2><p>ECMAScript，简称ES，是由Ecma国际（欧洲计算机制造商协会,英文名称是European Computer Manufacturers Association）按照标准制定的一种脚本语言规范。</p>
<p>JavaScript是按ECMAScript规范实现的一种脚本语言，JavaScript除了实现了ECMAScript规范，还提供了BOM和DOM的操作。</p>
<h2 id="ECMAScript版本历史"><a href="#ECMAScript版本历史" class="headerlink" title="ECMAScript版本历史"></a>ECMAScript版本历史</h2><ul>
<li><p>ES1.0, 1997年06月发布</p>
</li>
<li><p>ES2.0, 1997年06月发布</p>
</li>
<li><p>ES3.0, 1999年12月发布</p>
</li>
<li><p>ES4.0,  由于关于语言的复杂性出现了分歧。放弃发布</p>
</li>
<li><p>ES5.0, 2009年12月发布， 增加了严格模式，增加了少量语法，为ES6铺路</p>
</li>
<li><p>ES6.0, 2015年6月发布，增加了大量的新概念和语法特性</p>
<ul>
<li><strong>第六版的名字， 可以叫做ECMAScript6.0(ES), 也可以叫做ECMAScript 2015（ES2015）</strong></li>
<li>ECMA组织决定以后每年6月份都会发布一版新的语法标准，比如ES7(ECMAScript 2016) </li>
<li><strong>通过我们说的ES6泛指ES5之后的下一代标准，涵盖了ES6, ES7, ES8….</strong>  </li>
</ul>
</li>
</ul>
<h1 id="ES5-数组的新方法"><a href="#ES5-数组的新方法" class="headerlink" title="ES5-数组的新方法"></a>ES5-数组的新方法</h1><h2 id="forEach"><a href="#forEach" class="headerlink" title="forEach"></a>forEach</h2><p><code>forEach()</code> 方法对数组的每个元素执行一次提供的函数。功能等同于<code>for</code>循环.</p>
<p>应用场景：为一些相同的元素，绑定事件处理器！</p>
<p><strong>需求：遍历数组[“张飞”,”关羽”,”赵云”,”马超”]</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="string">"张飞"</span>,<span class="string">"关羽"</span>,<span class="string">"赵云"</span>,<span class="string">"马超"</span>];</span><br><span class="line"><span class="comment">//第一个参数：element，数组的每一项元素</span></span><br><span class="line"><span class="comment">//第二个参数：index，数组的下标</span></span><br><span class="line"><span class="comment">//第三个参数：array，正在遍历的数组</span></span><br><span class="line">arr.forEach(<span class="function"><span class="keyword">function</span>(<span class="params">element, index, array</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(element, index, array);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<h2 id="map"><a href="#map" class="headerlink" title="map"></a>map</h2><p><code>map()</code> 方法返回一个新数组，其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。</p>
<p><strong>需求：遍历数组，求每一项的平方存在于一个数组中</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>,<span class="number">4</span>,<span class="number">5</span>];  <span class="comment">// 1 4 9 16 25</span></span><br><span class="line"><span class="comment">//第一个参数：element，数组的每一项元素</span></span><br><span class="line"><span class="comment">//第二个参数：index，数组的下标</span></span><br><span class="line"><span class="comment">//第三个参数：array，正在遍历的数组</span></span><br><span class="line"><span class="comment">//返回值：一个新数组，每个元素都是回调函数的结果。</span></span><br><span class="line"><span class="keyword">var</span> newArray = arr.map(<span class="function"><span class="keyword">function</span>(<span class="params">element, index, array</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> element * element;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="built_in">console</span>.log(newArray);<span class="comment">//[1,4,9,16,25]</span></span><br></pre></td></tr></table></figure>



<h2 id="filter"><a href="#filter" class="headerlink" title="filter"></a>filter</h2><p><code>filter</code>用于过滤掉“不合格”的元素<br>返回一个新数组，如果在回调函数中返回true，那么就留下来，如果返回false，就扔掉</p>
<p><strong>需求：遍历数组，将数组中工资超过5000的值删除[1000, 5000, 20000, 3000, 10000, 800, 1500]</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">1000</span>, <span class="number">5000</span>, <span class="number">20000</span>, <span class="number">3000</span>, <span class="number">10000</span>, <span class="number">800</span>, <span class="number">1500</span>];</span><br><span class="line"><span class="comment">//第一个参数：element，数组的每一项元素</span></span><br><span class="line"><span class="comment">//第二个参数：index，数组的下标</span></span><br><span class="line"><span class="comment">//第三个参数：array，正在遍历的数组</span></span><br><span class="line"><span class="comment">//返回值：一个新数组，存储了所有返回true的元素</span></span><br><span class="line"><span class="keyword">var</span> newArray = arr.filter(<span class="function"><span class="keyword">function</span>(<span class="params">element, index, array</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> element &gt; <span class="number">5000</span>;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="built_in">console</span>.log(newArray);<span class="comment">//[1000, 5000, 3000, 800, 1500]</span></span><br></pre></td></tr></table></figure>



<h2 id="some"><a href="#some" class="headerlink" title="some"></a>some</h2><p><code>some</code>用于遍历数组，如果有至少一个满足条件，就返回true，否则返回false。</p>
<p><strong>需求：遍历数组，判断数组是否包含奇数，[2,4,6,8,10,9]</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> arr = [<span class="number">2</span>,<span class="number">4</span>,<span class="number">6</span>,<span class="number">8</span>,<span class="number">10</span>,<span class="number">21</span>];</span><br><span class="line"><span class="comment">//第一个参数：element，数组的每一项元素</span></span><br><span class="line"><span class="comment">//第二个参数：index，数组的下标</span></span><br><span class="line"><span class="comment">//第三个参数：array，正在遍历的数组</span></span><br><span class="line"><span class="comment">//返回值：布尔类型的值，只要有一个回调函数返回true，就返回true</span></span><br><span class="line"><span class="keyword">var</span> flag = arr.some(<span class="function"><span class="keyword">function</span>(<span class="params">element, index, array</span>)</span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(element, index, array);</span><br><span class="line">   <span class="keyword">return</span>  element % <span class="number">2</span> == <span class="number">0</span>;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="built_in">console</span>.log(flag);<span class="comment">//true</span></span><br></pre></td></tr></table></figure>



<h2 id="every"><a href="#every" class="headerlink" title="every"></a>every</h2><p><code>every</code>用于遍历数组，只有当所有的元素返回true，才返回true，否则返回false。</p>
<p><strong>需求：遍历数组，判断数组是否都是偶数，[2,4,6,8,10,9]</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"> <span class="keyword">var</span> arr = [<span class="number">2</span>,<span class="number">4</span>,<span class="number">6</span>,<span class="number">8</span>,<span class="number">10</span>,<span class="number">21</span>];</span><br><span class="line"> <span class="comment">//第一个参数：element，数组的每一项元素</span></span><br><span class="line"> <span class="comment">//第二个参数：index，数组的下标</span></span><br><span class="line"> <span class="comment">//第三个参数：array，正在遍历的数组</span></span><br><span class="line"> <span class="comment">//返回值：布尔类型的值，只有当所有的元素返回true，才返回true，否则返回false。</span></span><br><span class="line"> <span class="keyword">var</span> flag = arr.every(<span class="function"><span class="keyword">function</span>(<span class="params">element, index, array</span>)</span>&#123;</span><br><span class="line">   <span class="built_in">console</span>.log(element, index, array);</span><br><span class="line"><span class="keyword">return</span> element %<span class="number">2</span> == <span class="number">0</span>;</span><br><span class="line"> &#125;);</span><br><span class="line"> <span class="built_in">console</span>.log(flag); <span class="comment">//false</span></span><br></pre></td></tr></table></figure>



<h1 id="ES6"><a href="#ES6" class="headerlink" title="ES6"></a>ES6</h1><h2 id="变量"><a href="#变量" class="headerlink" title="变量"></a>变量</h2><blockquote>
<p>ES6中提供了两个声明变量的关键字：const 和 let </p>
</blockquote>
<h3 id="let的使用"><a href="#let的使用" class="headerlink" title="let的使用"></a>let的使用</h3><p>ES6 新增了<code>let</code>命令，用来声明变量。它的用法类似于<code>var</code>。</p>
<ul>
<li>let声明的变量只有在当前作用域有效</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&#123;</span><br><span class="line">  <span class="keyword">let</span> a = <span class="number">10</span>;</span><br><span class="line">  <span class="keyword">var</span> b = <span class="number">1</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">a <span class="comment">// ReferenceError: a is not defined.</span></span><br><span class="line">b <span class="comment">// 1</span></span><br></pre></td></tr></table></figure>

<ul>
<li>不存在变量提升</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// let 的情况</span></span><br><span class="line"><span class="built_in">console</span>.log(bar); <span class="comment">// 报错ReferenceError</span></span><br><span class="line"><span class="keyword">let</span> bar = <span class="number">2</span>;</span><br></pre></td></tr></table></figure>

<ul>
<li>不允许重复声明</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a = <span class="number">10</span>;</span><br><span class="line"><span class="keyword">let</span> a = <span class="number">1</span>;<span class="comment">//报错 Identifier 'a' has already been declared</span></span><br></pre></td></tr></table></figure>

<h3 id="const的使用"><a href="#const的使用" class="headerlink" title="const的使用"></a>const的使用</h3><p><code>const</code>声明一个只读的常量。常量：值不可以改变的量 </p>
<ul>
<li>const声明的量不可以改变</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> PI = <span class="number">3.1415</span>;</span><br><span class="line">PI = <span class="number">3</span>; <span class="comment">//报错</span></span><br></pre></td></tr></table></figure>

<ul>
<li>const声明的变量必须赋值</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> num;</span><br></pre></td></tr></table></figure>

<ul>
<li>如果const声明了一个对象，仅仅保证地址不变</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> obj = &#123;<span class="attr">name</span>:<span class="string">'zs'</span>&#125;;</span><br><span class="line">obj.age = <span class="number">18</span>;<span class="comment">//正确</span></span><br><span class="line">obj = &#123;&#125;;<span class="comment">//报错</span></span><br></pre></td></tr></table></figure>

<ul>
<li>其他用法和let一样</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 只能在当前代码块中使用</span><br><span class="line"><span class="number">2.</span> 不会提升</span><br><span class="line"><span class="number">3.</span> 不能重复</span><br></pre></td></tr></table></figure>

<h3 id="let与const的使用场景"><a href="#let与const的使用场景" class="headerlink" title="let与const的使用场景"></a>let与const的使用场景</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 如果声明的变量不需要改变，那么使用<span class="keyword">const</span></span><br><span class="line"><span class="number">2.</span> 如果声明的变量需要改变，那么用<span class="keyword">let</span></span><br><span class="line"><span class="number">3.</span> 学了<span class="keyword">const</span>和<span class="keyword">let</span>之后，尽量别用<span class="keyword">var</span></span><br></pre></td></tr></table></figure>



<h2 id="解构赋值"><a href="#解构赋值" class="headerlink" title="解构赋值"></a>解构赋值</h2><h3 id="数组解构"><a href="#数组解构" class="headerlink" title="数组解构"></a>数组解构</h3><p>以前，为变量赋值，只能直接指定值。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> a = <span class="number">1</span>;</span><br><span class="line"><span class="keyword">let</span> b = <span class="number">2</span>;</span><br><span class="line"><span class="keyword">let</span> c = <span class="number">3</span>;</span><br></pre></td></tr></table></figure>

<p>ES6 允许写成下面这样。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> [a, b, c] = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br></pre></td></tr></table></figure>

<p>解构默认值</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> [a = <span class="number">0</span>, b, c] = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>];</span><br></pre></td></tr></table></figure>

<h3 id="对象解构"><a href="#对象解构" class="headerlink" title="对象解构"></a>对象解构</h3><p>解构不仅可以用于数组，还可以用于对象。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> &#123; foo, bar &#125; = &#123; <span class="attr">foo</span>: <span class="string">'aaa'</span>, <span class="attr">bar</span>: <span class="string">'bbb'</span> &#125;;</span><br><span class="line">foo <span class="comment">// "aaa"</span></span><br><span class="line">bar <span class="comment">// "bbb"</span></span><br></pre></td></tr></table></figure>

<p>如果变量名与属性名不一致，必须写成下面这样。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> &#123; <span class="attr">foo</span>: baz &#125; = &#123; <span class="attr">foo</span>: <span class="string">'aaa'</span>, <span class="attr">bar</span>: <span class="string">'bbb'</span> &#125;;</span><br><span class="line">baz <span class="comment">// "aaa"</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> obj = &#123; <span class="attr">first</span>: <span class="string">'hello'</span>, <span class="attr">last</span>: <span class="string">'world'</span> &#125;;</span><br><span class="line"><span class="keyword">let</span> &#123; <span class="attr">first</span>: f, <span class="attr">last</span>: l &#125; = obj;</span><br><span class="line">f <span class="comment">// 'hello'</span></span><br><span class="line">l <span class="comment">// 'world'</span></span><br></pre></td></tr></table></figure>

<p>函数的参数也可以使用解构赋值。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">add</span>(<span class="params">[x, y]</span>)</span>&#123;</span><br><span class="line">  <span class="keyword">return</span> x + y;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">add([<span class="number">1</span>, <span class="number">2</span>]); <span class="comment">// 3</span></span><br></pre></td></tr></table></figure>

<h2 id="字符串"><a href="#字符串" class="headerlink" title="字符串"></a>字符串</h2><h3 id="模版字符串"><a href="#模版字符串" class="headerlink" title="模版字符串"></a>模版字符串</h3><p>传统的 JavaScript 语言，拼接字符串如下：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> str = <span class="string">"大家好， 我叫"</span> + name + <span class="string">",今年"</span> + age + <span class="string">"岁了, 是"</span> + sex + <span class="string">"生"</span></span><br></pre></td></tr></table></figure>

<p>上面这种写法相当繁琐不方便，ES6 引入了模板字符串解决这个问题。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> str = <span class="string">`大家好， 我叫<span class="subst">$&#123;name&#125;</span>, 今年<span class="subst">$&#123;age&#125;</span>岁了， 是<span class="subst">$&#123;sex&#125;</span>生`</span>;</span><br></pre></td></tr></table></figure>

<p>字符串模版的优点</p>
<ul>
<li>允许换行</li>
<li>可以使用插值  <code>${}</code></li>
</ul>
<h3 id="字符串方法"><a href="#字符串方法" class="headerlink" title="字符串方法"></a>字符串方法</h3><ul>
<li><strong>includes()</strong>：返回布尔值，表示是否找到了参数字符串。</li>
<li><strong>startsWith()</strong>：返回布尔值，表示参数字符串是否在原字符串的头部。</li>
<li><strong>endsWith()</strong>：返回布尔值，表示参数字符串是否在原字符串的尾部。</li>
</ul>
<h2 id="数组"><a href="#数组" class="headerlink" title="数组"></a>数组</h2><h3 id="find"><a href="#find" class="headerlink" title="find"></a>find</h3><p><strong>find是ES6新增的语法</strong></p>
<p><code>find()</code> 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 <a href="https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/undefined" target="_blank" rel="noopener"><code>undefined</code></a>。 </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取第一个大于10的数</span></span><br><span class="line"><span class="keyword">var</span> array1 = [<span class="number">5</span>, <span class="number">12</span>, <span class="number">8</span>, <span class="number">130</span>, <span class="number">44</span>];</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> found = array1.find(<span class="function"><span class="keyword">function</span>(<span class="params">element</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> element &gt; <span class="number">10</span>;</span><br><span class="line">&#125;);</span><br><span class="line"><span class="built_in">console</span>.log(found);</span><br></pre></td></tr></table></figure>

<h3 id="findIndex"><a href="#findIndex" class="headerlink" title="findIndex"></a>findIndex</h3><p><strong>findIndex是ES6新增的语法</strong></p>
<p><code>findIndex()</code>方法返回数组中满足提供的测试函数的第一个元素的<strong>索引</strong>。否则返回-1。 </p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 获取第一个大于10的下标</span></span><br><span class="line"><span class="keyword">var</span> array1 = [<span class="number">5</span>, <span class="number">12</span>, <span class="number">8</span>, <span class="number">130</span>, <span class="number">44</span>];</span><br><span class="line"></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">findFirstLargeNumber</span>(<span class="params">element</span>) </span>&#123;</span><br><span class="line">  <span class="keyword">return</span> element &gt; <span class="number">13</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="built_in">console</span>.log(array1.findIndex(findFirstLargeNumber));</span><br></pre></td></tr></table></figure>

<h2 id="对象"><a href="#对象" class="headerlink" title="对象"></a>对象</h2><h3 id="简写"><a href="#简写" class="headerlink" title="简写"></a>简写</h3><p>1- 在对象中，如果属性名和变量名相同的话，可以省略一个<br>2- 在对象中，方法也可以简写， 不写function </p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">   <span class="keyword">let</span> name = <span class="string">'zs'</span></span><br><span class="line">   <span class="keyword">let</span> age = <span class="number">18</span> </span><br><span class="line"></span><br><span class="line">   <span class="comment">// 在对象中，如果属性名和变量名相同的话，可以省略一个</span></span><br><span class="line">   <span class="comment">// 在对象中，方法也可以简写</span></span><br><span class="line"></span><br><span class="line">   <span class="keyword">let</span> obj = &#123;</span><br><span class="line">     name: name,</span><br><span class="line">     age: age</span><br><span class="line">   &#125;</span><br><span class="line"></span><br><span class="line">   <span class="keyword">let</span> obj = &#123;</span><br><span class="line">     gender: <span class="string">'男'</span>,</span><br><span class="line">     name,</span><br><span class="line">     age</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line">   <span class="comment">// 在对象中的方法可以简写</span></span><br><span class="line">   <span class="comment">// 不写function</span></span><br><span class="line">   <span class="keyword">let</span> obj = &#123;</span><br><span class="line">     <span class="comment">// say: function () &#123;&#125;</span></span><br><span class="line">     say(n1) &#123;</span><br><span class="line">       <span class="built_in">console</span>.log(n1)</span><br><span class="line">     &#125;</span><br><span class="line">   &#125;</span><br><span class="line">   </span><br><span class="line"><span class="comment">//调用</span></span><br><span class="line">   obj.say(<span class="number">1</span>)</span><br></pre></td></tr></table></figure>



<h3 id="展开运算符-…"><a href="#展开运算符-…" class="headerlink" title="展开运算符 …"></a>展开运算符 …</h3><blockquote>
<p>思考：</p>
<p> let arr1 = [11, 22, 33];  let  arr2=[‘one’, ‘two’, ‘three’]   合并成一个新数组   </p>
</blockquote>
<blockquote>
<p>展开运算符（spread operator）允许一个表达式在某处展开。展开运算符在多个参数（用于函数调用）或多个元素（用于数组字面量）或者多个变量（用于解构赋值）的地方可以使用 </p>
</blockquote>
<p>1-展开数组</p>
<p>2-展开数组</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 展开运算符:  ...</span></span><br><span class="line"><span class="keyword">const</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br><span class="line"><span class="built_in">console</span>.log(...arr)</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> arr = [<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]</span><br><span class="line"><span class="keyword">const</span> arr2 = [<span class="number">4</span>, <span class="number">5</span>, <span class="number">6</span>]</span><br><span class="line"><span class="keyword">const</span> newArr = [...arr, ...arr2, <span class="number">5</span>, <span class="number">6</span>, <span class="number">7</span>, ...arr]</span><br><span class="line"><span class="built_in">console</span>.log(newArr)</span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">// const result = Math.max(...arr)</span></span><br><span class="line"><span class="comment">// console.log(result)</span></span><br><span class="line"></span><br><span class="line"><span class="comment">// ...还可以展开一个对象</span></span><br><span class="line"><span class="keyword">const</span> obj = &#123;</span><br><span class="line">  name: <span class="string">'zs'</span>,</span><br><span class="line">  age: <span class="number">18</span>,</span><br><span class="line">  gender: <span class="string">'男'</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> obj1 = &#123;</span><br><span class="line">  money: <span class="number">100</span>,</span><br><span class="line">  house: <span class="string">'房子'</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> obj2 = &#123;</span><br><span class="line">  ...obj,</span><br><span class="line">  ...obj1,</span><br><span class="line">  sayHi() &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'哈哈'</span>)</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="built_in">console</span>.log(obj2)</span><br></pre></td></tr></table></figure>







<h2 id="函数-箭头函数"><a href="#函数-箭头函数" class="headerlink" title="函数-箭头函数"></a>函数-箭头函数</h2><p>ES6标准新增了一种新的函数：Arrow Function（箭头函数）。</p>
<p>为什么叫Arrow Function？因为它的定义用的就是一个箭头：</p>
<h3 id="基本使用"><a href="#基本使用" class="headerlink" title="基本使用"></a>基本使用</h3><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> fn = <span class="function"><span class="keyword">function</span>(<span class="params">x, y</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(x + y);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">相当于</span><br><span class="line"><span class="comment">//语法： (参数列表) =&gt; &#123;函数体&#125;</span></span><br><span class="line"><span class="keyword">var</span> fn = <span class="function">(<span class="params">x, y</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(x + y);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="参数详解"><a href="#参数详解" class="headerlink" title="参数详解"></a>参数详解</h3><ul>
<li>如果没有参数列表，使用()表示参数列表</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> sum = <span class="function"><span class="params">()</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'哈哈'</span>)</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">// 等同于：</span></span><br><span class="line"><span class="keyword">var</span> sum = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;    </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'哈哈'</span>)</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<ul>
<li>如果只有一个参数，可以省略()</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 等同于：</span></span><br><span class="line"><span class="keyword">var</span> sum = <span class="function"><span class="keyword">function</span>(<span class="params">n1</span>) </span>&#123;    </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'哈哈'</span>)</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> sum = <span class="function"><span class="params">n1</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'哈哈'</span>)</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<ul>
<li>如果有多个参数，需要使用()把参数列表括起来</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> sum = <span class="function"><span class="keyword">function</span>(<span class="params">n1, n2</span>) </span>&#123;    </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'哈哈'</span>)</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> sum = <span class="function">(<span class="params">n1, n2</span>) =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'哈哈'</span>)</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<h3 id="返回值详解"><a href="#返回值详解" class="headerlink" title="返回值详解"></a>返回值详解</h3><ul>
<li>如果箭头函数的代码块部分多于一条语句，就要使用大括号将它们括起来</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> sum = <span class="function"><span class="keyword">function</span>(<span class="params">n1</span>) </span>&#123;    </span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'哈哈'</span>)</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> sum = <span class="function"><span class="params">n1</span> =&gt;</span> &#123;</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">'哈哈'</span>)</span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<ul>
<li>如果函数体只有一行一句，那么可以省略{}和return</li>
</ul>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> fn = <span class="function"><span class="keyword">function</span>(<span class="params">n1, n2</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> n1 + n2;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> fn = <span class="function">(<span class="params">n1, n2</span>) =&gt;</span> n1 + n2;</span><br></pre></td></tr></table></figure>

<h3 id="案例"><a href="#案例" class="headerlink" title="案例"></a>案例</h3><ol>
<li>有一个数组<code>[1,3,5,7,9,2,4,6,8,10]</code>,请对数组进行排序</li>
<li>有一个数组<code>[&#39;a&#39;,&#39;ccc&#39;,&#39;bb&#39;,&#39;dddd&#39;]</code>,请按照字符串长度对数组进行排序</li>
<li>有一个数组，<code>[57,88,99,100,33,77]</code>,请保留60分以上的成绩，返回一个新的数组</li>
</ol>
<h3 id="箭头函数的注意点"><a href="#箭头函数的注意点" class="headerlink" title="箭头函数的注意点"></a>箭头函数的注意点</h3><ol>
<li>箭头函数内部没有this，因此箭头函数内部的this指向了外部的this</li>
<li>箭头函数不能作为构造函数，因为箭头函数没有this</li>
</ol>
<p>【定义一个对象，定时器打招呼】</p>
<p><strong>苦口婆心一下：箭头函数刚开始用，肯定会有点不习惯，但是任何东西都有一个习惯的过程，慢慢接受就好了，多用，多练</strong></p>
<h3 id="默认参数"><a href="#默认参数" class="headerlink" title="默认参数"></a>默认参数</h3><p>ES6 允许为函数的参数设置默认值，即直接写在参数定义的后面。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">log</span>(<span class="params">x, y = <span class="string">'World'</span></span>) </span>&#123;</span><br><span class="line">  <span class="built_in">console</span>.log(x, y);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">log(<span class="string">'Hello'</span>) <span class="comment">// Hello World</span></span><br><span class="line">log(<span class="string">'Hello'</span>, <span class="string">'China'</span>) <span class="comment">// Hello China</span></span><br><span class="line">log(<span class="string">'Hello'</span>, <span class="string">''</span>) <span class="comment">// Hello</span></span><br></pre></td></tr></table></figure>





<h1 id="综合大练习"><a href="#综合大练习" class="headerlink" title="综合大练习"></a>综合大练习</h1><p>给定一个数组</p>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> list = [</span><br><span class="line">  <span class="comment">// wu: 武力    zhi:智力</span></span><br><span class="line">  &#123; <span class="attr">id</span>: <span class="number">1</span>, <span class="attr">name</span>: <span class="string">'张飞'</span>, <span class="attr">wu</span>: <span class="number">97</span>, <span class="attr">zhi</span>: <span class="number">10</span> &#125;,</span><br><span class="line">  &#123; <span class="attr">id</span>: <span class="number">2</span>, <span class="attr">name</span>: <span class="string">'诸葛亮'</span>, <span class="attr">wu</span>: <span class="number">55</span>, <span class="attr">zhi</span>: <span class="number">99</span> &#125;,</span><br><span class="line">  &#123; <span class="attr">id</span>: <span class="number">3</span>, <span class="attr">name</span>: <span class="string">'赵云'</span>, <span class="attr">wu</span>: <span class="number">97</span>, <span class="attr">zhi</span>: <span class="number">66</span> &#125;,</span><br><span class="line">  &#123; <span class="attr">id</span>: <span class="number">4</span>, <span class="attr">name</span>: <span class="string">'周瑜'</span>, <span class="attr">wu</span>: <span class="number">80</span>, <span class="attr">zhi</span>: <span class="number">98</span> &#125;,</span><br><span class="line">  &#123; <span class="attr">id</span>: <span class="number">5</span>, <span class="attr">name</span>: <span class="string">'吕布'</span>, <span class="attr">wu</span>: <span class="number">100</span>, <span class="attr">zhi</span>: <span class="number">8</span> &#125;,</span><br><span class="line">  &#123; <span class="attr">id</span>: <span class="number">6</span>, <span class="attr">name</span>: <span class="string">'司马懿'</span>, <span class="attr">wu</span>: <span class="number">30</span>, <span class="attr">zhi</span>: <span class="number">98</span> &#125;</span><br><span class="line">]</span><br></pre></td></tr></table></figure>

<ul>
<li>得到一个新数组，只保留英雄的名字， <code>[&#39;张飞&#39;, &#39;诸葛亮&#39;, &#39;赵云&#39;, &#39;周瑜&#39;, &#39;吕布&#39;, &#39;司马懿&#39;]</code></li>
<li>得到一个新数组，新数组中只保留武力值超过90的英雄</li>
<li>删除数组中名字为周瑜的英雄    list.splice(从哪删，删几个)   findIndex()</li>
<li>判断数组中所有英雄的武力是否都超过60， 最终打印结果： <code>全是猛将</code>  <code>还有弱鸡</code>     使用两种方式实现</li>
<li>找到数组中id为2的英雄，求他的武力+智力的综合   find()</li>
</ul>
<h2 id="Set-数据类型"><a href="#Set-数据类型" class="headerlink" title="Set 数据类型"></a>Set 数据类型</h2><blockquote>
<p> let arr = [1, 2, 3, 4, 2, 3, 5 ]  如何去重？    </p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 答案：</span></span><br><span class="line">arr = [...new <span class="built_in">Set</span>(arr)];</span><br></pre></td></tr></table></figure>

<blockquote>
<p> <em>Set</em> 对象允许你存储任何类型的唯一值,无论是原始值或者是对象引用 ,　ES6提供了新的数据类型Set<strong>，</strong>Set对象不是数组， 可以用来保存对象或者基本类型， 所有保存的值都是唯一的 </p>
</blockquote>
<figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> <span class="keyword">set</span> = new Set();</span><br><span class="line"><span class="keyword">set</span>.add(1)  // &#123;<span class="number">1</span>&#125;</span><br><span class="line"><span class="keyword">set</span>.add(2)  // &#123;<span class="number">1</span>, <span class="number">2</span>&#125;</span><br><span class="line"><span class="keyword">set</span>.add(1)  // &#123;<span class="number">1</span>, <span class="number">2</span>&#125;</span><br><span class="line"><span class="comment">//或者 </span></span><br><span class="line"><span class="keyword">let</span> <span class="keyword">set</span> = new Set([1,2,3,4,4,4,4,4]);</span><br><span class="line">console.log(<span class="keyword">set</span>) // Set(4)  &#123;<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>, <span class="number">4</span>&#125; --&gt;对象</span><br><span class="line"><span class="built_in">console</span>.log([...set]); <span class="comment">//输出：[ 1, 2, 3, 4 ]  --&gt; 数组</span></span><br></pre></td></tr></table></figure>



<p>图谱：</p>
<p><img src="/blog/2018/04/09/ES6/ES601/ES601.png" alt></p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://dttx123.gitee.io/2018/03/03/Ajax/ajax/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
      <meta itemprop="name" content="大春哥">
      <meta itemprop="description" content="IT">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Starry Night">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blog/2018/03/03/Ajax/ajax/" class="post-title-link" itemprop="url">Ajax</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2018-03-03 00:00:00" itemprop="dateCreated datePublished" datetime="2018-03-03T00:00:00+08:00">2018-03-03</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-05-13 11:33:54" itemprop="dateModified" datetime="2020-05-13T11:33:54+08:00">2020-05-13</time>
              </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="Ajax-前后端的交互技术"><a href="#Ajax-前后端的交互技术" class="headerlink" title="Ajax  - 前后端的交互技术"></a>Ajax  - 前后端的交互技术</h1><h1 id="服务器的概念"><a href="#服务器的概念" class="headerlink" title="服务器的概念"></a>服务器的概念</h1><blockquote>
<p>前言：通俗的讲，能够提供某种服务的机器（计算机）称为服务器 </p>
</blockquote>
<p><img src="/blog/2018/03/03/Ajax/ajax/server.png" alt></p>
<h2 id="服务器软件"><a href="#服务器软件" class="headerlink" title="服务器软件"></a>服务器软件</h2><blockquote>
<p>使计算机具备提供某种服务能力的应用软件，称为服务器软件，<br>通过安装相应的服务软件，然后进行配置后就可以使计算具备了提供某种服务的能力。</p>
</blockquote>
<p>常见的服务器软件： <code>Apache服务器</code>、Nginx 服务器、IIS服务器、Tomcat服务器、 Node服务器等；</p>
<h2 id="web服务器"><a href="#web服务器" class="headerlink" title="web服务器"></a>web服务器</h2><p>即(web服务器)网站服务器，主要提供文档(文本、图片、视频、音频)浏览服务，一般安装Apache、Nginx服务器软件。</p>
<p>服务器可以结合某一编程语言处理业务逻辑，由此进行的开发，通常称之为<strong>服务端开发</strong>。 </p>
<p>常见后台开发的编程语言有： <code>php</code>、java、.net、Python、Ruby、Perl。</p>
<h1 id="客户端"><a href="#客户端" class="headerlink" title="客户端"></a>客户端</h1><blockquote>
<p>具有向服务器<strong>索取服务</strong>能力的终端，叫做客户端。</p>
</blockquote>
<ul>
<li>客户端：电脑、平板、手机安装了客户端软件，就可以称为客户端</li>
<li>客户端：安装客户端软件，<strong>索取服务</strong>的计算机</li>
<li>服务器：安装服务器软件，<strong>提供服务</strong>的计算机</li>
</ul>
<h2 id="客户端软件"><a href="#客户端软件" class="headerlink" title="客户端软件"></a>客户端软件</h2><p><img src="/blog/2018/03/03/Ajax/ajax/client.png" alt="test image size">{:width=”200px”}</p>
<p>对于前端工程师而言，主要接触到的客户端软件就是<strong>浏览器</strong>。</p>
<p>以浏览器为宿主环境，结合 HTML、CSS、Javascript等技术，而进行的一系列开发，通常称之为<strong>前端开发</strong>。</p>
<h2 id="服务器与客户端的关系"><a href="#服务器与客户端的关系" class="headerlink" title="服务器与客户端的关系"></a>服务器与客户端的关系</h2><p><img src="/blog/2018/03/03/Ajax/ajax/cs.png" alt></p>
<p>问题：我们写的html页面存放在哪里？</p>
<blockquote>
<p>在浏览器中展示的所有的资源， 都是存放在服务器中的， 当客户端向服务器发送请求后，服务器会将资源返回给浏览器进行渲染；</p>
</blockquote>
<h1 id="动态网页与静态网页"><a href="#动态网页与静态网页" class="headerlink" title="动态网页与静态网页"></a>动态网页与静态网页</h1><ul>
<li>静态网页：使用浏览器端语言进行编程，网站由静态代码（HTML.CSS,JS）组成。用户请求服务器上已经存在的页面，不需要进行业务逻辑的处理。 <img src="/blog/2018/03/03/Ajax/ajax/static.png" alt></li>
</ul>
<ul>
<li>动态网站 ：网页通过服务器的程序动态生成。用户可以和服务器进行交互（可以根据用户输入的不同信息，返回不同的运行结果），可以处理复杂的业务逻辑。<img src="/blog/2018/03/03/Ajax/ajax/dong.png" alt></li>
</ul>
<p><strong>总结</strong></p>
<pre><code>动态网站的 `动`指的是网站`数据的动` 而不是 `视觉上的动`;</code></pre><h1 id="网络基础"><a href="#网络基础" class="headerlink" title="网络基础"></a>网络基础</h1><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//思考：我的电脑如何去 访问京东淘宝网页的？</span></span><br></pre></td></tr></table></figure>

<h2 id="ip地址"><a href="#ip地址" class="headerlink" title="ip地址"></a>ip地址</h2><p>所谓IP地址就是给每个连接在互联网上的主机分配的一个32位地址。(就像每个人的身份证号码一样)</p>
<p>通过ip就可以找到具体的某一台计算机。</p>
<p>例 <code>192.168.1.110</code></p>
<p>弊端：没有规律，不方便记忆和推广</p>
<p>查看本机IP地址 <code>ping</code>、<code>ipconfig</code></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ping <span class="number">192.168</span><span class="number">.1</span><span class="number">.110</span>  <span class="comment">// 查看和某个同学的电脑是否连通</span></span><br></pre></td></tr></table></figure>

<p><strong>两种特殊的IP地址：</strong></p>
<p><strong>127.0.0.1</strong>作为本地测试的IP地址。本机测试时，客户端与服务器都安装在本地计算机上，数据无需任何网络传输。</p>
<p>192.168开头为局域网的地址。</p>
<h2 id="域名"><a href="#域名" class="headerlink" title="域名"></a>域名</h2><p>由于IP地址基于数字，不方便记忆，于是便用域名来代替IP地址，域名是一个IP地址的“好记的名字”</p>
<p>查看域名对应的IP地址 <code>ping</code></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ping jd.com  <span class="comment">//可以获取到京东的ip</span></span><br></pre></td></tr></table></figure>

<p><strong>特殊的域名</strong></p>
<p>​    <code>localhost</code>，意思为本地主机。这是一个保留域名，主要用于本地测试，对应IP地址为<code>127.0.0.1</code>。</p>
<h2 id="DNS服务器"><a href="#DNS服务器" class="headerlink" title="DNS服务器"></a>DNS服务器</h2><p>DNS（Domain Name System）因特网上作为域名和IP地址相互映射的一个分布式数据库， 能够使用户更方便的访问互联网，而不用去记住能够被机器直接读取的IP数串。</p>
<p>简单的说就是用于记录IP地址和域名之间的对应关系。</p>
<p>查找优先级 本机hosts文件、DNS服务器</p>
<p>ipconfig /flushdns 刷新DNS</p>
<p><img src="/blog/2018/03/03/Ajax/ajax/dns.png" alt></p>
<p>问题： 在浏览器输入<a href="http://www.jd.com" target="_blank" rel="noopener">www.jd.com</a>  到 浏览器返回html页面的执行过程是什么样的？</p>
<h2 id="端口"><a href="#端口" class="headerlink" title="端口"></a>端口</h2><p>端口号是计算机与外界通讯交流的出入口，每个端口对应不同的服务。</p>
<p>现实生活中，银行不同的窗口办理不同的业务。</p>
<p>查看端口占用情况 netstat -an</p>
<p>常见端口号 80、3306、21  </p>
<h2 id="本地hosts"><a href="#本地hosts" class="headerlink" title="本地hosts"></a>本地hosts</h2><blockquote>
<p>Hosts是一个没有扩展名的系统文件，可以用记事本等工具打开，其作用就是将一些常用的网址域名与其对应的IP地址建立一个关联“数据库”，当用户在浏览器中输入一个需要登录的网址时，系统会<strong>首先自动从Hosts文件中寻找对应的IP地址</strong>，一旦找到，系统会立即打开对应网页，如果没有找到，则系统会再将网址提交DNS域名解析服务器进行IP地址的解析。</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//hosts文件的地址：C:\Windows\System32\drivers\etc</span></span><br><span class="line"><span class="comment">//在浏览器中输入taobao.com的执行过程。</span></span><br></pre></td></tr></table></figure>

<p><img src="/blog/2018/03/03/Ajax/ajax/host.png" alt></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//hosts文件内容</span></span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span> localhost</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span> localhost</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>  study.com</span><br><span class="line"><span class="number">127.0</span><span class="number">.0</span><span class="number">.1</span>  www.study.com</span><br></pre></td></tr></table></figure>

<p>谈资</p>
<h1 id="搭建HTTP服务器"><a href="#搭建HTTP服务器" class="headerlink" title="搭建HTTP服务器"></a>搭建HTTP服务器</h1><h2 id="phpStudy介绍"><a href="#phpStudy介绍" class="headerlink" title="phpStudy介绍"></a>phpStudy介绍</h2><blockquote>
<p>phpStudy是一个PHP调试环境的程序集成包。<br>该程序包集成最新的Apache+PHP+MySQL,安装非常的简单</p>
</blockquote>
<p><img src="/blog/2018/03/03/Ajax/ajax/phpStudy.png" alt></p>
<h2 id="phpStudy的安装"><a href="#phpStudy的安装" class="headerlink" title="phpStudy的安装"></a>phpStudy的安装</h2><p>安装phpStudy，解压双击安装(<strong>非中文路径</strong>)，其它默认安装。</p>
<p><strong>推荐就安装在默认的目录下，一定不能有中文，否则肯定启动不起来。</strong></p>
<p><img src="/blog/2018/03/03/Ajax/ajax/phpStudy02.png" alt>;</p>
<h2 id="phpStudy的错误解决"><a href="#phpStudy的错误解决" class="headerlink" title="phpStudy的错误解决"></a>phpStudy的错误解决</h2><p>如果phpStudy启动发生错误，参数下列几点。</p>
<ul>
<li>一是防火墙拦截</li>
</ul>
<ul>
<li>二是 80端口已经被别的程序占用，如IIS，迅雷等；</li>
</ul>
<ul>
<li><p>三是没有安装VC9运行库,php和apache都是VC9编译。</p>
<p>解决以上三个问题，99%能一次性安装成功 </p>
</li>
</ul>
<p>为了减少出错安装路径不得有<strong>汉字</strong>，如有防火墙开启，会提示是否信任httpd、mysqld运行，请选择全部允许。 </p>
<h3 id="关闭IIS服务器"><a href="#关闭IIS服务器" class="headerlink" title="关闭IIS服务器"></a>关闭IIS服务器</h3><p>如果发现服务器启动不成功，很大原因是端口被占用了，因为windows默认会有一个iis服务器，只需要把iis服务器给禁用了即可。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//控制面板--&gt;程序--&gt;程序与功能--&gt;启用或关闭windows功能</span></span><br></pre></td></tr></table></figure>

<p><img src="/blog/2018/03/03/Ajax/ajax/iis.png" alt></p>
<h3 id="提示缺少vc9-库文件"><a href="#提示缺少vc9-库文件" class="headerlink" title="提示缺少vc9 库文件"></a>提示缺少vc9 库文件</h3><p>在提供的资料库中找到<strong>phpStudy运行库</strong>， 根据自己电脑操作系统的位数安装对应的vc9运行库即可。</p>
<p><img src="/blog/2018/03/03/Ajax/ajax/vc9.png" alt></p>
<h3 id="关闭防火墙"><a href="#关闭防火墙" class="headerlink" title="关闭防火墙"></a>关闭防火墙</h3><p>如果希望系统自己的服务器能够被别人访问。需要关闭防火墙。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//控制面板---&gt;系统和安全---&gt;Windows 防火墙---&gt;启动或者关闭windows防火墙</span></span><br></pre></td></tr></table></figure>



<h1 id="PHP基础"><a href="#PHP基础" class="headerlink" title="PHP基础"></a>PHP基础</h1><p><strong>PHP简介</strong></p>
<ul>
<li>开源（open source）软件，跨平台，常用操作系统稳定执行。Windows / Linux。做WEB开发的经典组合 WAMP,LAMP基本都是开源软件</li>
</ul>
<ul>
<li>入门简单,用户只需要关注应用，开发成本低</li>
</ul>
<ul>
<li>支持的大多数主流数据库。MySQL，oracle,Redis等<br>​</li>
</ul>
<blockquote>
<p>文件以.php后缀结尾，所有程序包含在<code>&lt;?php 这里写代码 ?&gt;</code><br>避免使用中文目录和中文文件名 </p>
<p>php页面无法直接打开需要运行在服务器环境当中</p>
</blockquote>
<p><strong><em>注意：学习php的目的是为了更好的学习前端技能，因为需要了解一些后台的知识，千万不要本末倒置，我们的课程重心在前端。</em></strong> </p>
<h2 id="php初体验"><a href="#php初体验" class="headerlink" title="php初体验"></a>php初体验</h2><figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line">  	<span class="comment">//echo 相当于document.write</span></span><br><span class="line">    <span class="keyword">echo</span> <span class="string">"hello world"</span>;</span><br><span class="line"><span class="meta">?&gt;</span></span><br></pre></td></tr></table></figure>

<p>输入中文乱码问题：如果使用echo输出中文，会乱码。</p>
<p><strong><em>在php的语法中，末尾必须加分号，不然就报错了（最后一行可以不加分号）</em></strong></p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">&lt;?php</span></span><br><span class="line">    <span class="comment">//content-Type:text/html;返回内容是一个HTML文档，这样设置后，就能识别HTML标签了。</span></span><br><span class="line">    <span class="comment">//charset=utf-8 设置编码集</span></span><br><span class="line">    header(<span class="string">"content-Type:text/html;charset=utf-8"</span>);</span><br><span class="line">    <span class="keyword">echo</span> <span class="string">"hello world"</span>;</span><br><span class="line">    <span class="keyword">echo</span> <span class="string">"&lt;br/&gt;"</span>;</span><br><span class="line">    <span class="keyword">echo</span> <span class="string">"大家好，我是春哥"</span>;</span><br><span class="line"><span class="meta">?&gt;</span></span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//思考：浏览器访问php文件时，过程是怎么样的？</span></span><br></pre></td></tr></table></figure>



<h2 id="变量"><a href="#变量" class="headerlink" title="变量"></a>变量</h2><blockquote>
<p>php是一门弱类型语法，变量的类型可以随意改变。<br>变量其实就是存储数据的容器</p>
</blockquote>
<p><strong>变量的命名规则</strong></p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1. 不需要关键字进行声明，变量在第一次赋值的时候被创建。</span></span><br><span class="line"><span class="comment">//2. 必须以$符号开始</span></span><br><span class="line"><span class="comment">//3. $后面的命名规则与js的变量命名规则一致。</span></span><br><span class="line">$name = <span class="string">"春哥"</span>;</span><br><span class="line"><span class="keyword">echo</span> $name;</span><br></pre></td></tr></table></figure>



<h2 id="数据类型"><a href="#数据类型" class="headerlink" title="数据类型"></a>数据类型</h2><h3 id="简单数据类型"><a href="#简单数据类型" class="headerlink" title="简单数据类型"></a>简单数据类型</h3><p><strong>字符串</strong> </p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$str = <span class="string">"春哥"</span>;</span><br><span class="line"><span class="keyword">echo</span> $str;</span><br></pre></td></tr></table></figure>

<p><strong>整数</strong> </p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$num = <span class="number">100</span>;</span><br><span class="line"><span class="keyword">echo</span> $num;</span><br></pre></td></tr></table></figure>

<p><strong>浮点型</strong> </p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">$float = <span class="number">11.11</span>;</span><br><span class="line"><span class="keyword">echo</span> $float;</span><br></pre></td></tr></table></figure>

<p><strong>布尔类型</strong> </p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">$flag = <span class="keyword">true</span>;</span><br><span class="line"><span class="comment">//当布尔类型值为true时，输出1</span></span><br><span class="line"><span class="keyword">echo</span> $flag;</span><br><span class="line">$flag = <span class="keyword">false</span>;</span><br><span class="line"><span class="comment">//当布尔类型为false时，输出空字符串</span></span><br><span class="line"><span class="keyword">echo</span> $flag;</span><br></pre></td></tr></table></figure>

<p><strong>字符串连接符</strong> </p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1. 在php中，+号只有算数的功能，并不能拼串</span></span><br><span class="line"><span class="comment">//2. 在php中，拼串使用.</span></span><br><span class="line">$name = <span class="string">"春哥"</span>;</span><br><span class="line"><span class="keyword">echo</span> <span class="string">"大家好，我是"</span> . $name . <span class="string">"，今年18岁"</span>;</span><br></pre></td></tr></table></figure>

<p><strong>php中的单引号与双引号</strong></p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1. 字符串的定义可以使用单引号，也可以使用双引号</span></span><br><span class="line">$name = <span class="string">"春哥"</span>;</span><br><span class="line">$desc = <span class="string">'很帅'</span>;</span><br><span class="line"><span class="comment">//2. 双引号可以解析变量</span></span><br><span class="line"><span class="comment">//3. 单引号的性能会高于双引号（了解）</span></span><br><span class="line"></span><br><span class="line">$name = <span class="string">"春哥"</span>;<span class="comment">//春哥</span></span><br><span class="line"><span class="keyword">echo</span> $name;</span><br><span class="line">$desc = <span class="string">'很帅'</span>;</span><br><span class="line"><span class="keyword">echo</span> $desc;<span class="comment">//很帅</span></span><br><span class="line"></span><br><span class="line">$str = <span class="string">'$name 很帅'</span>;<span class="comment">//$name 很帅</span></span><br><span class="line"><span class="keyword">echo</span> $str;</span><br><span class="line"></span><br><span class="line">$str = <span class="string">"$name 很帅"</span>;<span class="comment">//春哥 很帅</span></span><br><span class="line"><span class="keyword">echo</span> $str;</span><br></pre></td></tr></table></figure>



<h3 id="数组"><a href="#数组" class="headerlink" title="数组"></a>数组</h3><blockquote>
<p>在php中，数组分为两种，索引数组和关联数组</p>
<p>计算数组长度的方法： count(数组名);</p>
</blockquote>
<p><strong>索引数组（类似与JS中的数组）</strong></p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">$arr = <span class="keyword">array</span>(<span class="string">"张飞"</span>,<span class="string">"赵云"</span>,<span class="string">"马超"</span>);</span><br><span class="line"><span class="keyword">echo</span> $arr;<span class="comment">//echo只能打印基本数据类型</span></span><br><span class="line"><span class="keyword">echo</span> $arr[<span class="number">0</span>];<span class="comment">//张飞</span></span><br></pre></td></tr></table></figure>

<p><strong>关联数组（类似与JS中的对象）</strong> </p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//属性名必须用引号引起来</span></span><br><span class="line">$arr = <span class="keyword">array</span>(<span class="string">"name"</span>=&gt;<span class="string">"zhangsan"</span>, <span class="string">"age"</span>=&gt;<span class="number">18</span>);</span><br><span class="line"><span class="keyword">echo</span> $arr[<span class="string">"name"</span>];</span><br></pre></td></tr></table></figure>

<p><strong>输出语句</strong> </p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1. echo 输出简单数据类型</span></span><br><span class="line"><span class="comment">//2. print_r 输出数据结构，一般用于输出复杂类型。</span></span><br><span class="line">print_r($arr);<span class="comment">//print_r是一个函数，不要忘记小括号</span></span><br></pre></td></tr></table></figure>


<h2 id="语句"><a href="#语句" class="headerlink" title="语句"></a>语句</h2><h3 id="判断语句"><a href="#判断语句" class="headerlink" title="判断语句"></a>判断语句</h3><p>基本上来说，所有语言的if..else语法都是一样</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">$age = <span class="number">17</span>;</span><br><span class="line"><span class="keyword">if</span> ($age &gt;= <span class="number">18</span>) &#123;</span><br><span class="line">  <span class="keyword">echo</span> <span class="string">"终于可以看电影了,嘿嘿嘿"</span>;</span><br><span class="line">&#125; <span class="keyword">else</span> &#123;</span><br><span class="line">  <span class="keyword">echo</span> <span class="string">"哎，还是回家学习吧"</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="循环语句"><a href="#循环语句" class="headerlink" title="循环语句"></a>循环语句</h3><p><strong>遍历索引数组</strong> </p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line">$arr = <span class="keyword">array</span>(<span class="string">"张三"</span>, <span class="string">"李四"</span>, <span class="string">"王五"</span>, <span class="string">"赵六"</span>, <span class="string">"田七"</span>, <span class="string">"王八"</span>);</span><br><span class="line"><span class="comment">//获取数组的长度： count($arr)</span></span><br><span class="line"><span class="keyword">for</span>($i = <span class="number">0</span>; $i &lt; count($arr); $i++) &#123;</span><br><span class="line">  <span class="keyword">echo</span> $arr[$i];</span><br><span class="line">  <span class="keyword">echo</span> <span class="string">"&lt;br&gt;"</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>遍历关联数组</strong> </p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//遍历关联数组</span></span><br><span class="line">$arr = <span class="keyword">array</span>(</span><br><span class="line">  <span class="string">"name"</span>=&gt;<span class="string">"zs"</span>,</span><br><span class="line">  <span class="string">"age"</span>=&gt;<span class="number">18</span>,</span><br><span class="line">  <span class="string">"sex"</span>=&gt;<span class="number">20</span></span><br><span class="line">);</span><br><span class="line"><span class="keyword">foreach</span>($arr <span class="keyword">as</span> $key =&gt; $value) &#123;</span><br><span class="line">  <span class="keyword">echo</span> $key . <span class="string">"="</span> . $value . <span class="string">"&lt;br&gt;"</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h1 id="表单提交"><a href="#表单提交" class="headerlink" title="表单提交"></a>表单提交</h1><p><img src="/blog/2018/03/03/Ajax/ajax/form.png" alt></p>
<blockquote>
<p>表单（form）：表单用于收集用户输入信息，并将数据提交给服务器。是一种常见的与服务端数据交互的一种方式</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1. action：指定表单的提交地址</span></span><br><span class="line"><span class="comment">//2. method:指定表单的提交方式，get/post，默认get</span></span><br><span class="line"><span class="comment">//3. input的数据想要提交到后台，必须指定name属性，后台通过name属性获取值</span></span><br><span class="line"><span class="comment">//4. 想要提交表单，不能使用input:button 必须使用input:submit</span></span><br></pre></td></tr></table></figure>

<p><strong>php获取表单数据</strong> </p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F;$_GET是PHP系统提供的一个超全局变量，是一个数组，里面存放了表单通过get方式提交的数据。</span><br><span class="line">&#x2F;&#x2F;$_POST是PHP系统提供的一个超全局变量，是一个数组，里面存放了表单通过post方式提交的数据。</span><br></pre></td></tr></table></figure>

<p><strong>get与post的区别</strong> </p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1. get方式</span></span><br><span class="line">	<span class="comment">//1.1 数据会拼接在url地址的后面?username=hcc&amp;password=123456</span></span><br><span class="line">	<span class="comment">//1.2 地址栏有长度限制，因此get方式提交数据大小不会超过4k</span></span><br><span class="line"><span class="comment">//2. post方式</span></span><br><span class="line">	<span class="comment">//2.1 数据不会在url中显示，相比get方式，post更安全</span></span><br><span class="line">	<span class="comment">//2.2 提交的数据没有大小限制</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//根据HTTP规范，GET用于信息获取，POST表示可能修改变服务器上的资源的请求</span></span><br></pre></td></tr></table></figure>



<h1 id="http协议"><a href="#http协议" class="headerlink" title="http协议"></a>http协议</h1><blockquote>
<p>协议是指计算机通信网络中两台计算机之间进行通信所必须共同遵守的规定或规则<br>HTTP协议，即超文本传输协议(Hypertext transfer protocol)。是一种详细规定了浏览器和服务器之间互相通信的规则，HTTP协议分为<strong>请求</strong> 和<strong>响应</strong> 两个部分组成。</p>
</blockquote>
<h2 id="请求与请求报文"><a href="#请求与请求报文" class="headerlink" title="请求与请求报文"></a>请求与请求报文</h2><p><strong>get请求的请求报文详解</strong> </p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//--------------------------请求行--------------------------------</span></span><br><span class="line"><span class="comment">// GET  请求方式</span></span><br><span class="line"><span class="comment">// /day02/01.php?username=hucc&amp;password=123456    请求路径+参数（注意点）</span></span><br><span class="line"><span class="comment">// HTTP/1.1 HTTP的版本号</span></span><br><span class="line">GET /day02/<span class="number">01.</span>php?username=hucc&amp;password=<span class="number">123456</span> HTTP/<span class="number">1.1</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//--------------------------请求头--------------------------------</span></span><br><span class="line"><span class="comment">// Host:主机地址</span></span><br><span class="line">Host: www.study.com</span><br><span class="line"><span class="comment">// HTTP1.1版本默认开启，建立过连接后，TCP连接不会断开，下次连接可以继续使用（底层，不用管）</span></span><br><span class="line">Connection: keep-alive</span><br><span class="line"><span class="comment">//chrome浏览器自己增加的，不用管</span></span><br><span class="line">Upgrade-Insecure-Requests: <span class="number">1</span></span><br><span class="line"><span class="comment">//浏览器的代理字符串（版本信息）</span></span><br><span class="line">User-Agent: Mozilla/<span class="number">5.0</span> (Windows NT <span class="number">10.0</span>; WOW64) AppleWebKit/<span class="number">537.36</span> (KHTML, like Gecko) Chrome/<span class="number">58.0</span><span class="number">.3029</span><span class="number">.96</span> Safari/<span class="number">537.36</span></span><br><span class="line"><span class="comment">//浏览器端可以接受的类型。</span></span><br><span class="line">Accept: text/html,application/xhtml+xml,application/xml;q=<span class="number">0.9</span>,image/webp,<span class="string">`*/*`</span>;q=<span class="number">0.8</span></span><br><span class="line"><span class="comment">//从哪个页面发出的请求</span></span><br><span class="line">Referer: http:<span class="comment">//www.study.com/day02/01-login.html</span></span><br><span class="line"><span class="comment">//检查浏览器支持的压缩方式</span></span><br><span class="line">Accept-Encoding: gzip, deflate, sdch</span><br><span class="line"><span class="comment">//浏览器支持的语言，优先中文。</span></span><br><span class="line">Accept-Language: zh-CN,zh;q=<span class="number">0.8</span>,en;q=<span class="number">0.6</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//----------------------------请求体-------------------------------------</span></span><br><span class="line"><span class="comment">//get请求没有请求体，但是参数会拼接到请求行中</span></span><br></pre></td></tr></table></figure>



<p><strong>POST请求的请求报文</strong> </p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//-----------------------请求行---------------------------------------------</span></span><br><span class="line">POST /day02/<span class="number">01.</span>php HTTP/<span class="number">1.1</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//-----------------------请求头--------------------------------------------</span></span><br><span class="line">Host: www.study.com</span><br><span class="line">Connection: keep-alive</span><br><span class="line"><span class="comment">//传递的参数的长度。</span></span><br><span class="line">Content-Length: <span class="number">29</span></span><br><span class="line">Cache-Control: max-age=<span class="number">0</span></span><br><span class="line">Origin: http:<span class="comment">//www.study.com</span></span><br><span class="line">Upgrade-Insecure-Requests: <span class="number">1</span></span><br><span class="line">User-Agent: Mozilla/<span class="number">5.0</span> (Windows NT <span class="number">10.0</span>; WOW64) AppleWebKit/<span class="number">537.36</span> (KHTML, like Gecko) Chrome/<span class="number">58.0</span><span class="number">.3029</span><span class="number">.96</span> Safari/<span class="number">537.36</span></span><br><span class="line"><span class="comment">//内容类型：表单数据，如果是post请求，必须指定这个属性。</span></span><br><span class="line">Content-Type: application/x-www-form-urlencoded</span><br><span class="line">Accept: text/html,application/xhtml+xml,application/xml;q=<span class="number">0.9</span>,image/webp,<span class="string">`*/*`</span>;q=<span class="number">0.8</span></span><br><span class="line">Referer: http:<span class="comment">//www.study.com/day02/01-login.html</span></span><br><span class="line">Accept-Encoding: gzip, deflate</span><br><span class="line">Accept-Language: zh-CN,zh;q=<span class="number">0.8</span>,en;q=<span class="number">0.6</span></span><br><span class="line"></span><br><span class="line"><span class="comment">//------------------------请求体------------------------------------------</span></span><br><span class="line">username=hucc&amp;password=<span class="number">123456</span></span><br></pre></td></tr></table></figure>

<p><strong>GET请求与POST请求的对比</strong> </p>
<ul>
<li>GET请求没有请求体，因为GET请求的参数拼接到地址栏中了</li>
<li>POST请求有请求体，就是传递的参数</li>
<li>POST请求需要指定content-type属性。</li>
</ul>
<h2 id="响应与响应报文"><a href="#响应与响应报文" class="headerlink" title="响应与响应报文"></a>响应与响应报文</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//---------------------状态行（响应行）-------------------------------</span></span><br><span class="line"><span class="comment">//HTTP/1.1  HTTP版本</span></span><br><span class="line"><span class="comment">//200 响应的状态</span></span><br><span class="line">	<span class="comment">//200表示成功</span></span><br><span class="line">	<span class="comment">//304表示读缓存</span></span><br><span class="line">	<span class="comment">//404表示找不到资源</span></span><br><span class="line">	<span class="comment">//500表示服务端错误</span></span><br><span class="line">HTTP/<span class="number">1.1</span> <span class="number">200</span> OK</span><br><span class="line"></span><br><span class="line"><span class="comment">//----------------------响应头-----------------------------------------------</span></span><br><span class="line"><span class="built_in">Date</span>: Thu, <span class="number">22</span> Jun <span class="number">2017</span> <span class="number">16</span>:<span class="number">51</span>:<span class="number">22</span> GMT</span><br><span class="line">Server: Apache/<span class="number">2.4</span><span class="number">.23</span> (Win32) OpenSSL/<span class="number">1.0</span><span class="number">.2</span>j PHP/<span class="number">5.4</span><span class="number">.45</span></span><br><span class="line">X-Powered-By: PHP/<span class="number">5.4</span><span class="number">.45</span></span><br><span class="line">Content-Length: <span class="number">18</span></span><br><span class="line">Keep-Alive: timeout=<span class="number">5</span>, max=<span class="number">100</span></span><br><span class="line">Connection: Keep-Alive</span><br><span class="line"><span class="comment">//内容类型，告诉浏览器该如何解析响应结果</span></span><br><span class="line">Content-Type: text/html;charset=utf<span class="number">-8</span></span><br><span class="line"><span class="comment">//-----------------------响应体------------------------------------------------</span></span><br><span class="line">用户登录成功</span><br></pre></td></tr></table></figure>

<p>通常来说，我们不会用抓包工具来查看请求和响应，太麻烦了，可以直接使用谷歌浏览器来查看请求报文和响应报文。</p>
<p>谷歌浏览器会对报文进行一定的格式化，看起来虽然不是原生的报文，但是使用起来更加的方便简洁。</p>
<h1 id="AJAX"><a href="#AJAX" class="headerlink" title="AJAX"></a>AJAX</h1><blockquote>
<p>即 Asynchronous [e’sɪŋkrənəs] Javascript And XML， AJAX 不是一门的新的语言，而是对现有技术的综合利用。 本质是在HTTP协议的基础上以异步的方式与服务器进行通信。</p>
</blockquote>
<h2 id="同步与异步"><a href="#同步与异步" class="headerlink" title="同步与异步"></a>同步与异步</h2><p>同步和异步概念：</p>
<p>同步: 指的就是事情要一件一件做。等做完前一件才能做后一件任务</p>
<p>异步: 不受当前任务的影响，两件事情同时进行，做一件事情时，不影响另一件事情的进行。</p>
<p>编程中：异步程序代码执行时不会阻塞其它程序代码执行,从而提升整体执行效率。</p>
<p>ajax技术的应用：</p>
<ol>
<li>验证你的用户名是否已经存在（一边输入，一边获取你的信息，和后台比对）。</li>
<li>百度搜索提示，及相关内容展示（一边输入，一边找出了你可能要的内容）。</li>
</ol>
<p>XMLHttpRequest可以以异步方式的处理程序。</p>
<h2 id="XMLHttpRequest"><a href="#XMLHttpRequest" class="headerlink" title="XMLHttpRequest"></a>XMLHttpRequest</h2><blockquote>
<p>浏览器内建对象，用于与服务器通信(交换数据) ， 由此我们便可实现对网页的部分更新，而不是刷新整个页面。这个请求是异步，即在往服务器发送请求时，并不会阻碍程序的运行，浏览器会继续渲染后续的结构。</p>
</blockquote>
<h3 id="发送get请求"><a href="#发送get请求" class="headerlink" title="发送get请求"></a>发送get请求</h3><p>XMLHttpRequest以异步的方式发送HTTP请求，因此在发送请求时，一样需要遵循HTTP协议。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用XMLHttpRequest发送get请求的步骤</span></span><br><span class="line"><span class="comment">//1. 创建一个XMLHttpRequest对象</span></span><br><span class="line"><span class="keyword">var</span> xhr = <span class="keyword">new</span> XMLHttpRequest;<span class="comment">//构造函数没有参数的情况,括号可以省略</span></span><br><span class="line"><span class="comment">//2. 设置请求行</span></span><br><span class="line"><span class="comment">//第一个参数:请求方式  get/post</span></span><br><span class="line"><span class="comment">//第二个参数:请求的地址 需要在url后面拼上参数列表</span></span><br><span class="line">xhr.open(<span class="string">"get"</span>, <span class="string">"08.php?name=hucc"</span>);</span><br><span class="line"><span class="comment">//3. 设置请求头</span></span><br><span class="line"><span class="comment">//浏览器会给我们默认添加基本的请求头,get请求时无需设置</span></span><br><span class="line"><span class="comment">//4. 设置请求体</span></span><br><span class="line"><span class="comment">//get请求的请求体为空,因为参数列表拼接到url后面了</span></span><br><span class="line">xhr.send(<span class="literal">null</span>);</span><br></pre></td></tr></table></figure>

<ul>
<li>get请求,设置请求行时,需要把参数列表拼接到url后面</li>
<li>get请求不用设置请求头</li>
<li>get请求的请求体为null</li>
</ul>
<h3 id="发送post请求"><a href="#发送post请求" class="headerlink" title="发送post请求"></a>发送post请求</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> xhr = <span class="keyword">new</span> XMLHttpRequest;</span><br><span class="line"><span class="comment">//1. 设置请求行 post请求的参数列表在请求体中</span></span><br><span class="line">xhr.open(<span class="string">"post"</span>, <span class="string">"09.php"</span>);</span><br><span class="line"><span class="comment">//2. 设置请求头, post请求必须设置content-type,不然后端无法获取到数据</span></span><br><span class="line">xhr.setRequestHeader(<span class="string">"content-type"</span>, <span class="string">"application/x-www-form-urlencoded"</span>);</span><br><span class="line"><span class="comment">//3. 设置请求体</span></span><br><span class="line">xhr.send(<span class="string">"name=hucc&amp;age=18"</span>);</span><br></pre></td></tr></table></figure>

<ul>
<li>post请求,设置请求行时,参数列表不能拼接到url后面</li>
<li>post必须设置请求头中的content-type为application/x-www-form-urlencoded</li>
<li>post请求需要将参数列表设置到请求体中.</li>
</ul>
<h3 id="获取响应"><a href="#获取响应" class="headerlink" title="获取响应"></a>获取响应</h3><p>HTTP响应分为3个部分，状态行、响应头、响应体。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//给xhr注册一个onload事件，当xhr的状态发生状态发生改变时，会触发这个事件。</span></span><br><span class="line">xhr.onload = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123; </span><br><span class="line">    <span class="comment">//1. 获取状态行</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"状态行:"</span>+xhr.status);</span><br><span class="line">    <span class="comment">//2. 获取响应头</span></span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"所有的相应头:"</span>+xhr.getAllResponseHeaders());</span><br><span class="line">    <span class="built_in">console</span>.log(<span class="string">"指定相应头:"</span>+xhr.getResponseHeader(<span class="string">"content-type"</span>));</span><br><span class="line">    <span class="comment">//3. 获取响应体</span></span><br><span class="line">    <span class="built_in">console</span>.log(xhr.responseText);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h2 id="数据交互"><a href="#数据交互" class="headerlink" title="数据交互"></a>数据交互</h2><blockquote>
<p>浏览器端只是负责用户的交互和数据的收集以及展示，真正的数据都是存储在服务器端的。我们现在通过ajax的确可以返回一些简单的数据（一个字符串），但是在实际开发过程中，肯定会会设计到大量的复杂类型的数据传输，比如数组、对象等，但是每个编程语言的语法都不一样。因此我们会采用通过的数据交换格式（XML、JSON）来进行数据的交互。</p>
</blockquote>
<h3 id="XML"><a href="#XML" class="headerlink" title="XML"></a>XML</h3><p><strong>什么是XML</strong></p>
<ul>
<li>XML 指可扩展标记语言（EXtensible Markup Language）</li>
<li>XML 是一种标记语言，很类似 HTML</li>
<li>XML 的设计宗旨是传输数据，而非显示数据</li>
<li>XML 标签没有被预定义。您需要自行定义标签。</li>
</ul>
<p><strong>语法规范</strong></p>
<ul>
<li>第一行必须是版本信息</li>
<li>必须有一个根元素（有且仅有一个）</li>
<li>标签不可有空格、不可以数字或.开头、大小写敏感</li>
<li>不可交叉嵌套，都是双标签，如果是单标签，必须闭合</li>
<li>属性双引号（浏览器自动修正成双引号了）</li>
<li>特殊符号要使用实体</li>
<li>注释和HTML一样</li>
</ul>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">students</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">student</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">name</span>&gt;</span>张三<span class="tag">&lt;/<span class="name">name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">age</span>&gt;</span>18<span class="tag">&lt;/<span class="name">age</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">gender</span>&gt;</span>男<span class="tag">&lt;/<span class="name">gender</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">desc</span>&gt;</span>路人甲<span class="tag">&lt;/<span class="name">desc</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">student</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">student</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">name</span>&gt;</span>李四<span class="tag">&lt;/<span class="name">name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">age</span>&gt;</span>20<span class="tag">&lt;/<span class="name">age</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">gender</span>&gt;</span>男<span class="tag">&lt;/<span class="name">gender</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">desc</span>&gt;</span>路人乙<span class="tag">&lt;/<span class="name">desc</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">student</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">students</span>&gt;</span></span><br></pre></td></tr></table></figure>



<p><strong>html解析xml</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//获取服务端返回的xml数据，需要使用xhr.responseXML，这是一个document对象，可以使用DOM中的方法查找元素。</span></span><br><span class="line"><span class="keyword">var</span> data = xhr.responseXML;</span><br><span class="line"><span class="comment">//获取所有的学生</span></span><br><span class="line"><span class="keyword">var</span> students = data.querySelectorAll(<span class="string">"student"</span>);</span><br></pre></td></tr></table></figure>

<p>缺点：虽然可以描述和传输复杂数据，但是其解析过于复杂并且体积较大，所以实现开发已经很少使用了。</p>
<h3 id="JSON数据"><a href="#JSON数据" class="headerlink" title="JSON数据"></a>JSON数据</h3><p>JSON(JavaScript Object Notation, JS 对象标记) 是一种轻量级的数据交换格式。它基于 ECMAScript 规范的一个子集，采用完全独立于编程语言的文本格式来存储和表示数据。</p>
<ul>
<li>数据在名称/值对中</li>
<li>数据由逗号分隔(最后一个健/值对不能带逗号)</li>
<li>花括号保存对象，方括号保存数组</li>
<li>键使用双引号</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> obj = &#123;<span class="attr">a</span>: <span class="string">'Hello'</span>, <span class="attr">b</span>: <span class="string">'World'</span>&#125;; <span class="comment">//这是一个对象，注意键名也是可以使用引号包裹的</span></span><br><span class="line"><span class="keyword">var</span> json = <span class="string">'&#123;"a": "Hello", "b": "World"&#125;'</span>; <span class="comment">//这是一个 JSON 字符串，本质是一个字符串</span></span><br></pre></td></tr></table></figure>

<p><strong>JSON数据在不同语言进行传输时，类型为字符串，不同的语言各自也都对应有解析方法，需要解析完成后才能读取</strong></p>
<h4 id="php处理json"><a href="#php处理json" class="headerlink" title="php处理json"></a>php处理json</h4><ul>
<li>php关联数组==&gt; json</li>
</ul>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// php的关联数组</span></span><br><span class="line">$obj = <span class="keyword">array</span>(</span><br><span class="line">  <span class="string">"a"</span>=&gt;<span class="string">"hello"</span>,</span><br><span class="line">  <span class="string">"b"</span>=&gt;<span class="string">"world"</span>,</span><br><span class="line">  <span class="string">"name"</span>=&gt;<span class="string">"胡聪聪"</span></span><br><span class="line">);</span><br><span class="line"><span class="comment">//json字符串</span></span><br><span class="line">$json = json_encode($obj);</span><br><span class="line"><span class="keyword">echo</span> $json;</span><br></pre></td></tr></table></figure>

<ul>
<li>json===&gt;php对象</li>
</ul>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">$json = <span class="string">'&#123;"a": "Hello", "b": "World"&#125;'</span>;<span class="comment">//json字符串</span></span><br><span class="line"><span class="comment">//第一个参数：json字符串</span></span><br><span class="line"><span class="comment">//第二个参数：</span></span><br><span class="line">	<span class="comment">//false，将json转换成对象(默认)</span></span><br><span class="line">	<span class="comment">//true：将对象转换成数组(推荐)</span></span><br><span class="line">$obj = json_decode($json,<span class="keyword">true</span>);</span><br><span class="line"><span class="keyword">echo</span> $obj[<span class="string">'a'</span>];</span><br><span class="line"></span><br><span class="line"><span class="comment">//通过json文件获取到的内容就是一个json字符串。</span></span><br><span class="line">$data = file_get_contents(<span class="string">"data.json"</span>);</span><br><span class="line"><span class="comment">//将json转换成数组</span></span><br><span class="line">$result = json_decode($data, <span class="keyword">true</span>);</span><br><span class="line">print_r($result);</span><br></pre></td></tr></table></figure>



<h4 id="JS处理json"><a href="#JS处理json" class="headerlink" title="JS处理json"></a>JS处理json</h4><ul>
<li>JS对象 ==&gt; JSON字符串 JSON.stringify(obj)</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//obj是一个js对象</span></span><br><span class="line"><span class="keyword">var</span> obj = &#123;<span class="attr">a</span>: <span class="string">'Hello'</span>, <span class="attr">b</span>: <span class="string">'World'</span>&#125;</span><br><span class="line"><span class="comment">//result就变成了一个json字符串了</span></span><br><span class="line"><span class="keyword">var</span> result = <span class="built_in">JSON</span>.stringify(obj);<span class="comment">// '&#123;"a": "Hello", "b": "World"&#125;'</span></span><br></pre></td></tr></table></figure>

<ul>
<li>JSON字符串 ==&gt; JS对象  JSON.parse(obj)</li>
</ul>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//json是一个json字符串</span></span><br><span class="line"><span class="keyword">var</span> json = <span class="string">'&#123;"a": "Hello", "b": "World"&#125;'</span>;</span><br><span class="line"><span class="comment">//obj就变成了一个js对象</span></span><br><span class="line"><span class="keyword">var</span> obj = <span class="built_in">JSON</span>.parse(json);<span class="comment">// &#123;a: 'Hello', b: 'World'&#125;</span></span><br></pre></td></tr></table></figure>



<p>使用json进行数据传输</p>
<p>思考：</p>
<ol>
<li>js有一个对象，如何发送到php后台</li>
<li>php中有一个对象，如何发送到前台。</li>
</ol>
<p>【案例：获取表格数据.html】</p>
<h2 id="兼容性处理"><a href="#兼容性处理" class="headerlink" title="兼容性处理"></a>兼容性处理</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> xhr = <span class="literal">null</span>;</span><br><span class="line"><span class="keyword">if</span>(XMLHttpRequest)&#123;</span><br><span class="line">  <span class="comment">//现代浏览器</span></span><br><span class="line">  xhr = <span class="keyword">new</span>  XMLHttpRequest();</span><br><span class="line">&#125;<span class="keyword">else</span>&#123;</span><br><span class="line">  <span class="comment">//IE5.5支持</span></span><br><span class="line">  xmlHttp=<span class="keyword">new</span> ActiveXObject(<span class="string">"Microsoft.XMLHTTP"</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>前后端分离</strong></p>
<p>​    我们使用php动态渲染页面时，有很多比较麻烦的地方。</p>
<ul>
<li>在前端写好页面以后，需要后台进行修改，意味这后端程序员也需要懂前端的知识，其实渲染的工作应该交给前端来做。</li>
<li>前端没有写好页面的话，后端无法开始工作，需要等待前端的页面完成之后才能开始工作，拖延项目 的进度。</li>
<li>在客户端设备多元化的情况下，后台渲染的页面无法满足所有用户的需求</li>
<li>前后端代码混合在一个文件中，项目修改和维护成本高​</li>
</ul>
<h2 id="jQuery中的ajax方法"><a href="#jQuery中的ajax方法" class="headerlink" title="jQuery中的ajax方法"></a>jQuery中的ajax方法</h2><blockquote>
<p>jQuery为我们提供了更强大的Ajax封装</p>
</blockquote>
<h3 id="ajax"><a href="#ajax" class="headerlink" title="$.ajax"></a>$.ajax</h3><p>参数列表</p>
<table>
<thead>
<tr>
<th>参数名称</th>
<th>描述</th>
<th>取值</th>
<th>示例</th>
</tr>
</thead>
<tbody><tr>
<td>url</td>
<td>接口地址</td>
<td></td>
<td>url:”02.php”</td>
</tr>
<tr>
<td>type</td>
<td>请求方式</td>
<td>get/post</td>
<td>type:”get”</td>
</tr>
<tr>
<td>timeout</td>
<td>超时时间</td>
<td>单位毫秒</td>
<td>timeout:5000</td>
</tr>
<tr>
<td>dataType</td>
<td>服务器返回的格式</td>
<td>json/xml/text(默认)</td>
<td>dataType:”json”</td>
</tr>
<tr>
<td>data</td>
<td>发送的请求数据</td>
<td>对象</td>
<td>data:{name:”zs”, age:18}</td>
</tr>
<tr>
<td>beforeSend</td>
<td>调用前的回调函数</td>
<td>function(){}</td>
<td>beforeSend:function(){ alert(1) }</td>
</tr>
<tr>
<td>success</td>
<td>成功的回调函数</td>
<td>function (data) {}</td>
<td>success:function (data) {}</td>
</tr>
<tr>
<td>error</td>
<td>失败的回调函数</td>
<td>function (error) {}</td>
<td>error:function(data) {}</td>
</tr>
<tr>
<td>complete</td>
<td>完成后的回调函数</td>
<td>function () {}</td>
<td>complete:function () {}</td>
</tr>
</tbody></table>
<p>使用示例：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line">$.ajax(&#123;</span><br><span class="line">  type:<span class="string">"get"</span>,<span class="comment">//请求类型</span></span><br><span class="line">  url:<span class="string">"02.php"</span>,<span class="comment">//请求地址</span></span><br><span class="line">  data:&#123;<span class="attr">name</span>:<span class="string">"zs"</span>, <span class="attr">age</span>:<span class="number">18</span>&#125;,<span class="comment">//请求数据</span></span><br><span class="line">  dataType:<span class="string">"json"</span>,<span class="comment">//希望接受的数据类型</span></span><br><span class="line">  timeout:<span class="number">5000</span>,<span class="comment">//设置超时时间</span></span><br><span class="line">  beforeSend:<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">//alert("发送前调用");</span></span><br><span class="line">  &#125;,</span><br><span class="line">  success:<span class="function"><span class="keyword">function</span> (<span class="params">data</span>) </span>&#123;</span><br><span class="line">    <span class="comment">//alert("成功时调用");</span></span><br><span class="line">    <span class="built_in">console</span>.log(data);</span><br><span class="line">  &#125;,</span><br><span class="line">  error:<span class="function"><span class="keyword">function</span> (<span class="params">error</span>) </span>&#123;</span><br><span class="line">    <span class="comment">//alert("失败时调用");</span></span><br><span class="line">    <span class="built_in">console</span>.log(error);</span><br><span class="line">  &#125;,</span><br><span class="line">  complete:<span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="comment">//alert("请求完成时调用");</span></span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>【案例：登录案例.html】</p>
<h3 id="其他api-了解"><a href="#其他api-了解" class="headerlink" title="其他api(了解)"></a>其他api(了解)</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//$.post(url, callback, [dataType]);只发送post请求</span></span><br><span class="line"><span class="comment">//$.get(url, callback, [dataType]);</span></span><br><span class="line"><span class="comment">//$.getJSON(url, callback);</span></span><br><span class="line"><span class="comment">//$.getScript(url,callback);//载入服务器端的js文件</span></span><br><span class="line"><span class="comment">//$("div").load(url);//载入一个服务器端的html页面。</span></span><br></pre></td></tr></table></figure>



<h3 id="接口化开发"><a href="#接口化开发" class="headerlink" title="接口化开发"></a>接口化开发</h3><p>请求地址即所谓的接口，通常我们所说的接口化开发，其实是指一个接口对应一个功能， 并且严格约束了<strong>请求参数</strong> 和<strong>响应结果</strong> 的格式，这样前后端在开发过程中，可以减少不必要的讨论， 从而并行开发，可以极大的提升开发效率，另外一个好处，当网站进行改版后，服务端接口进行调整时，并不影响到前端的功能。</p>
<h4 id="注册接口"><a href="#注册接口" class="headerlink" title="注册接口"></a>注册接口</h4><p><strong>表单序列化</strong></p>
<p>jquery提供了一个<code>serialize()</code>方法序列化表单，说白就是将表单中带有name属性的所有参数拼成一个格式为<code>name=value&amp;name1=value1</code>这样的字符串。方便我们获取表单的数据。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//serialize将表单参数序列化成一个字符串。必须指定name属性</span></span><br><span class="line"><span class="comment">//name=hucc&amp;pass=123456&amp;repass=123456&amp;mobile=18511249258&amp;code=1234</span></span><br><span class="line">$(<span class="string">'form'</span>).serialize();</span><br></pre></td></tr></table></figure>

<p><strong>jquery的ajax方法，data参数能够直接识别表单序列化的数据<code>data:$(&#39;form&#39;).serialize()</code></strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">$.post(&#123;</span><br><span class="line">  url:<span class="string">"register.php"</span>,</span><br><span class="line">  data:$(<span class="string">'form'</span>).serialize(),</span><br><span class="line">  dataType:<span class="string">'json'</span>,</span><br><span class="line">  success:<span class="function"><span class="keyword">function</span> (<span class="params">info</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(info);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>



<p><strong>需求文档</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//注册功能</span></span><br><span class="line"><span class="comment">//总需求：点击注册按钮，向服务端发送请求</span></span><br><span class="line"><span class="comment">//需求1:表单校验</span></span><br><span class="line">  <span class="comment">//1.1 用户名不能为空，否则提示"请输入用户名"</span></span><br><span class="line">  <span class="comment">//1.2 密码不能为空，否则提示"请输入密码"</span></span><br><span class="line">  <span class="comment">//1.3 确认密码必须与密码一直，否则提示"确认密码与密码不一致"</span></span><br><span class="line">  <span class="comment">//1.4 手机号码不能为空，否则提示"请输入手机号码";</span></span><br><span class="line">  <span class="comment">//1.5 手机号码格式必须正确，否则提示"手机号格式错误"</span></span><br><span class="line">  <span class="comment">//1.6 短信验证码必须是4位的数字，否则提示"验证码格式错误"</span></span><br><span class="line"><span class="comment">//需求2：点击注册按钮时，按钮显示为"注册中...",并且不能重复提交请求</span></span><br><span class="line"><span class="comment">//需求3：根据不同响应结果，处理响应</span></span><br><span class="line">	 <span class="comment">//3.1显示注册结果</span></span><br></pre></td></tr></table></figure>



<h1 id="模板引擎"><a href="#模板引擎" class="headerlink" title="模板引擎"></a>模板引擎</h1><blockquote>
<p>是为了使用户界面与业务数据（内容）分离而产生的，它可以生成特定格式的文档，用于网站的模板引擎就会生成一个标准的HTML文档。</p>
</blockquote>
<h2 id="为什么要使用模板引擎"><a href="#为什么要使用模板引擎" class="headerlink" title="为什么要使用模板引擎"></a>为什么要使用模板引擎</h2><p>我们通过ajax获取到数据后，需要把数据渲染到页面，在学习模板引擎前，我们的做法是大量的拼接字符串，对于结构简单的页面，这么做还行，但是如果页面结构很复杂，使用拼串的话<strong>代码可阅读性非常的差，而且非常容易出错，后期代码维护也是相当的麻烦。</strong> </p>
<p>【演示：使用拼串进行渲染的缺点.html】</p>
<p>作用：代替前面渲染数据是拼接字符串操作</p>
<p>实际工作渲染数据使用的模板引擎 </p>
<h2 id="常见的模板引擎"><a href="#常见的模板引擎" class="headerlink" title="常见的模板引擎"></a>常见的模板引擎</h2><p>BaiduTemplate：<a href="http://tangram.baidu.com/BaiduTemplate/" target="_blank" rel="noopener">http://tangram.baidu.com/BaiduTemplate/</a><br>velocity.js：<a href="https://github.com/shepherdwind/velocity.js/" target="_blank" rel="noopener">https://github.com/shepherdwind/velocity.js/</a><br>ArtTemplate：<a href="https://github.com/aui/artTemplate" target="_blank" rel="noopener">https://github.com/aui/artTemplate</a></p>
<p>artTemplate是使用最广泛，效率最高的模板引擎，需要大家掌握。</p>
<h2 id="artTemplate的使用"><a href="#artTemplate的使用" class="headerlink" title="artTemplate的使用"></a>artTemplate的使用</h2><p><a href="https://github.com/aui/art-template" target="_blank" rel="noopener">github地址</a></p>
<p><a href="https://aui.github.io/art-template/docs/" target="_blank" rel="noopener">中文api地址</a></p>
<h3 id="artTemplate入门"><a href="#artTemplate入门" class="headerlink" title="artTemplate入门"></a>artTemplate入门</h3><p><strong>1.引入模板引擎的js文件</strong> </p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;script src=<span class="string">"template-web.js"</span>&gt;&lt;<span class="regexp">/script&gt;</span></span><br></pre></td></tr></table></figure>

<p><strong>2.准备模板</strong> </p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--</span></span><br><span class="line"><span class="comment">  指定了type为text/template后，这一段script标签并不会解析，也不会显示。</span></span><br><span class="line"><span class="comment">--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">type</span>=<span class="string">"text/template"</span> <span class="attr">id</span>=<span class="string">"tmp"</span>&gt;</span></span><br><span class="line"><span class="handlebars"><span class="xml">  <span class="tag">&lt;<span class="name">p</span>&gt;</span>姓名：</span><span class="template-variable">&#123;&#123; username &#125;&#125;</span><span class="xml"><span class="tag">&lt;/<span class="name">p</span>&gt;</span>  </span></span></span><br><span class="line"><span class="handlebars"><span class="xml">  <span class="tag">&lt;<span class="name">p</span>&gt;</span>年龄：</span><span class="template-variable">&#123;&#123; age &#125;&#125;</span><span class="xml"><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span></span><br><span class="line"><span class="handlebars"><span class="xml">  <span class="tag">&lt;<span class="name">p</span>&gt;</span>技能：</span><span class="template-variable">&#123;&#123; skill &#125;&#125;</span><span class="xml"><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span></span><br><span class="line"><span class="handlebars"><span class="xml">  <span class="tag">&lt;<span class="name">p</span>&gt;</span>描述：</span><span class="template-variable">&#123;&#123;desc &#125;&#125;</span><span class="xml"><span class="tag">&lt;/<span class="name">p</span>&gt;</span></span></span></span><br><span class="line"><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<p><strong>3.准备数据</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//3. 准备数据,数据是后台获取的，可以随时变化</span></span><br><span class="line"><span class="keyword">var</span> json = &#123;</span><br><span class="line">  userName:<span class="string">"隔壁老王"</span>,</span><br><span class="line">  age:<span class="number">18</span>,</span><br><span class="line">  skill:<span class="string">"查水表"</span>,</span><br><span class="line">  desc:<span class="string">"年轻气壮"</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><strong>4.将模板与数据进行绑定</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//第一个参数：模板的id</span></span><br><span class="line"><span class="comment">//第二个参数：数据</span></span><br><span class="line"><span class="comment">//返回值：根据模板生成的字符串。</span></span><br><span class="line"><span class="keyword">var</span> html = template(<span class="string">"myTmp"</span>, json);</span><br><span class="line"><span class="built_in">console</span>.log(html);</span><br></pre></td></tr></table></figure>

<p><strong>5.将数据显示到页面</strong></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> div = <span class="built_in">document</span>.querySelector(<span class="string">"div"</span>);</span><br><span class="line">div.innerHTML = html;</span><br></pre></td></tr></table></figure>

<p><strong>注意：传递给模板引擎的数据必须是对象</strong></p>
<h3 id="artTemplate语法"><a href="#artTemplate语法" class="headerlink" title="artTemplate语法"></a>artTemplate语法</h3><p><strong>if语法</strong></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&#123;&#123;if gender='男'&#125;&#125;</span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"man"</span>&gt;</span></span><br><span class="line">&#123;&#123;else&#125;&#125;</span><br><span class="line">  <span class="tag">&lt;<span class="name">div</span> <span class="attr">class</span>=<span class="string">"woman"</span>&gt;</span></span><br><span class="line">&#123;&#123;/if&#125;&#125;</span><br></pre></td></tr></table></figure>

<p><strong>each语法</strong></p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--</span></span><br><span class="line"><span class="comment">  1. &#123;&#123;each data&#125;&#125;  可以通过$value 和 $index获取值和下标</span></span><br><span class="line"><span class="comment">  2. &#123;&#123;each data v i&#125;&#125;  自己指定值为v，下标为i</span></span><br><span class="line"><span class="comment">--&gt;</span></span><br><span class="line">&#123;&#123;each data v i&#125;&#125;</span><br><span class="line"><span class="tag">&lt;<span class="name">li</span>&gt;</span></span><br><span class="line">  <span class="tag">&lt;<span class="name">a</span> <span class="attr">href</span>=<span class="string">"&#123;&#123;v.url&#125;&#125;"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"&#123;&#123;v.src&#125;&#125;"</span> <span class="attr">alt</span>=<span class="string">""</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">p</span>&gt;</span>&#123;&#123;v.content&#125;&#125;<span class="tag">&lt;/<span class="name">p</span>&gt;</span></span><br><span class="line">   <span class="tag">&lt;/<span class="name">a</span>&gt;</span></span><br><span class="line"> <span class="tag">&lt;/<span class="name">li</span>&gt;</span></span><br><span class="line">&#123;&#123;/each&#125;&#125;</span><br></pre></td></tr></table></figure>

<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//如果返回的数据是个数组，必须使用对象进行包裹，因为在&#123;&#123;&#125;&#125;中只写书写对象的属性。</span></span><br><span class="line"><span class="keyword">var</span> html = template(<span class="string">"navTmp"</span>, &#123;<span class="attr">data</span>:info&#125;);</span><br></pre></td></tr></table></figure>



<h1 id="同源与跨域"><a href="#同源与跨域" class="headerlink" title="同源与跨域"></a>同源与跨域</h1><h2 id="同源"><a href="#同源" class="headerlink" title="同源"></a>同源</h2><p>不同源 则跨域 </p>
<h3 id="同源策略的基本概念"><a href="#同源策略的基本概念" class="headerlink" title="同源策略的基本概念"></a>同源策略的基本概念</h3><blockquote>
<p>1995年，同源政策由 Netscape 公司引入浏览器。目前，所有浏览器都实行这个政策。<br>同源策略：最初，它的含义是指，A网页设置的 Cookie，B网页不能打开，除非这两个网页”同源”。现在浏览器的所谓”同源”指的是”三个相同”:</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">协议相同</span><br><span class="line">域名相同</span><br><span class="line">端口相同</span><br></pre></td></tr></table></figure>

<p>举例来说，<code>http://www.example.com/dir/page.html</code>这个网址，协议是<code>http://</code>，域名是<code>www.example.com</code>，端口是<code>80</code>（默认端口可以省略）。它的同源情况如下。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//http://www.example.com/dir2/other.html：同源</span></span><br><span class="line"><span class="comment">//http://example.com/dir/other.html：不同源（域名不同）</span></span><br><span class="line"><span class="comment">//http://v2.www.example.com/dir/other.html：不同源（域名不同）</span></span><br><span class="line"><span class="comment">//http://www.example.com:81/dir/other.html：不同源（端口不同）</span></span><br></pre></td></tr></table></figure>

<h3 id="同源策略的目的"><a href="#同源策略的目的" class="headerlink" title="同源策略的目的"></a>同源策略的目的</h3><blockquote>
<p>同源政策的目的，是为了保证用户信息的安全，防止恶意的网站窃取数据。</p>
</blockquote>
<h3 id="同源策略的限制范围"><a href="#同源策略的限制范围" class="headerlink" title="同源策略的限制范围"></a>同源策略的限制范围</h3><blockquote>
<p>随着互联网的发展，“同源策略”越来越严格，目前，如果非同源，以下三种行为都将收到限制。</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1. Cookie、LocalStorage 无法读取。</span></span><br><span class="line"><span class="comment">//2. DOM 无法获得。</span></span><br><span class="line"><span class="comment">//3. AJAX 请求不能发送。</span></span><br></pre></td></tr></table></figure>

<p>虽然这些限制是很有必要的，但是也给我们日常开发带来不好的影响。比如实际开发过程中，往往都会把服务器端架设到一台甚至是一个集群的服务器中，把客户端页面放到另外一个单独的服务器。那么这时候就会出现不同源的情况，如果我们知道两个网站都是安全的话，我们是希望两个不同源的网站之间可以相互请求数据的。这就需要使用到<strong>跨域</strong> 。</p>
<h2 id="跨域"><a href="#跨域" class="headerlink" title="跨域"></a>跨域</h2><p>【演示跨域问题.html】</p>
<h3 id="jsonp"><a href="#jsonp" class="headerlink" title="jsonp"></a>jsonp</h3><blockquote>
<p>JSONP(JSON with Padding)、可用于解决主流浏览器的跨域数据访问的问题。原理：服务端返回一个预先定义好的javascript函数的调用，并且将服务器的数据以该函数参数的形式传递过来，这个方法需要前后端配合。</p>
</blockquote>
<p><code>script</code> 标签是不受同源策略的限制的，它可以载入任意地方的 JavaScript 文件，而并不要求同源。类似的还有<code>img</code>和<code>link</code>标签</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">&lt;!--不受同源策略的标签--&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">img</span> <span class="attr">src</span>=<span class="string">"http://www.api.com/1.jpg"</span> <span class="attr">alt</span>=<span class="string">""</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"stylesheet"</span> <span class="attr">href</span>=<span class="string">"http://www.api.com/1.css"</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">script</span> <span class="attr">src</span>=<span class="string">"http://www.api.com/1.js"</span>&gt;</span><span class="tag">&lt;/<span class="name">script</span>&gt;</span></span><br></pre></td></tr></table></figure>

<h4 id="jsonp演化过程"><a href="#jsonp演化过程" class="headerlink" title="jsonp演化过程"></a>jsonp演化过程</h4><p>jsonp原理大家知道即可，不用太过于去纠结这个原理，因此jquery已经帮我们封装好了，我们使用起来非常的方便。</p>
<h3 id="jquery对于jsonp的封装"><a href="#jquery对于jsonp的封装" class="headerlink" title="jquery对于jsonp的封装"></a>jquery对于jsonp的封装</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用起来相当的简单，跟普通的get请求没有任何的区别，只需要把dataType固定成jsonp即可。</span></span><br><span class="line">$.ajax(&#123;</span><br><span class="line">  type:<span class="string">"get"</span>,</span><br><span class="line">  url:<span class="string">"http://www.api.com/testjs.php"</span>,</span><br><span class="line">  dataType:<span class="string">"jsonp"</span>,</span><br><span class="line">  data:&#123;</span><br><span class="line">    uname:<span class="string">"hucc"</span>,</span><br><span class="line">    upass:<span class="string">"123456"</span></span><br><span class="line">  &#125;,</span><br><span class="line">  success:<span class="function"><span class="keyword">function</span> (<span class="params">info</span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(info);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p>【案例：查询天气.html】</p>
<p><a href="http://lbsyun.baidu.com/index.php?title=car/api/weather" target="_blank" rel="noopener">http://lbsyun.baidu.com/index.php?title=car/api/weather</a></p>
<p><a href="https://www.jisuapi.com/api/weather/" target="_blank" rel="noopener">天气查询api地址</a></p>
<p>秘钥：zVo5SStav7IUiVON0kuCogecm87lonOj</p>
<p>图灵机器人：<a href="http://www.tuling123.com/" target="_blank" rel="noopener">http://www.tuling123.com/</a></p>
<h1 id="XMLHttpRequest-2-0"><a href="#XMLHttpRequest-2-0" class="headerlink" title="XMLHttpRequest 2.0"></a>XMLHttpRequest 2.0</h1><blockquote>
<p>XMLHttpRequest是一个javascript内置对象，使得Javascript可以进行异步的HTTP通信。2008年2月，就提出了XMLHttpRequest Level 2 草案。</p>
</blockquote>
<p>老版本的XMLHttpRequest的缺点：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1. 仅支持传输文本数据，无法传说二进制文件，比如图片视频等。</span></span><br><span class="line"><span class="comment">//2. 传输数据时，没有进度信息，只能提示完成与否。</span></span><br><span class="line"><span class="comment">//3. 受到了"同源策略"的限制</span></span><br></pre></td></tr></table></figure>



<p>新版本的功能：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1. 可以设置timeout 超时时间</span></span><br><span class="line"><span class="comment">//2. 可以使用formData对象管理表单数据</span></span><br><span class="line"><span class="comment">//3. 可以获取数据传输的进度信息</span></span><br></pre></td></tr></table></figure>

<p><strong>注意：我们现在使用new XMLHttpRequest创建的对象就是2.0对象了，我们之前学的是1.0的语法，现在学习一些2.0的新特性即可。</strong>  </p>
<h2 id="timeout设置超时"><a href="#timeout设置超时" class="headerlink" title="timeout设置超时"></a>timeout设置超时</h2><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">xhr.timeout = <span class="number">3000</span>;<span class="comment">//设置超时时间</span></span><br><span class="line">xhr.ontimeout = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">  alert(<span class="string">"请求超时"</span>);</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h2 id="formData管理表单数据"><a href="#formData管理表单数据" class="headerlink" title="formData管理表单数据"></a>formData管理表单数据</h2><blockquote>
<p>formData对象类似于jquery的serialize方法，用于管理表单数据</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//使用特点： </span></span><br><span class="line"><span class="comment">//1. 实例化一个formData对象， new formData(form); form就是表单元素</span></span><br><span class="line"><span class="comment">//4. formData对象可以直接作为 xhr.send(formData)的参数。注意此时数据是以二进制的形式进行传输。</span></span><br><span class="line"><span class="comment">//5. formData有一个append方法，可以添加参数。formData.append("id", "1111");</span></span><br><span class="line"><span class="comment">//6. 这种方式只能以post形式传递，不需要设置请求头，浏览器会自动为我们设置一个合适的请求头。</span></span><br></pre></td></tr></table></figure>



<p>代码示例：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1. 使用formData必须发送post请求</span></span><br><span class="line">    xhr.open(<span class="string">"post"</span>, <span class="string">"02-formData.php"</span>);</span><br><span class="line">    </span><br><span class="line"><span class="comment">//2. 获取表单元素</span></span><br><span class="line"><span class="keyword">var</span> form = <span class="built_in">document</span>.querySelector(<span class="string">"#myForm"</span>);</span><br><span class="line"><span class="comment">//3. 创建form对象，可以直接作为send的参数。</span></span><br><span class="line"><span class="keyword">var</span> formData = <span class="keyword">new</span> FormData(form);</span><br><span class="line"></span><br><span class="line"><span class="comment">//4. formData可以使用append方法添加参数</span></span><br><span class="line">formData.append(<span class="string">"id"</span>, <span class="string">"1111"</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//5. 发送，不需要指定请求头，浏览器会自动选择合适的请求头</span></span><br><span class="line">xhr.send(formData);</span><br></pre></td></tr></table></figure>



<h2 id="文件上传"><a href="#文件上传" class="headerlink" title="文件上传"></a>文件上传</h2><blockquote>
<p>以前，文件上传需要借助表单进行上传，但是表单上传是同步的，也就是说文件上传时，页面需要提交和刷新，用户体验不友好，xhr2.0中的formData对象支持文件的异步上传。</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> formData = <span class="keyword">new</span> FormData();</span><br><span class="line"><span class="comment">//获取上传的文件，传递到后端</span></span><br><span class="line"><span class="keyword">var</span> file = <span class="built_in">document</span>.getElementById(<span class="string">"file"</span>).files[<span class="number">0</span>];</span><br><span class="line">formData.append(<span class="string">"file"</span>, file);</span><br><span class="line">xhr.send(formData);</span><br></pre></td></tr></table></figure>



<h2 id="显示文件进度信息"><a href="#显示文件进度信息" class="headerlink" title="显示文件进度信息"></a>显示文件进度信息</h2><blockquote>
<p>xhr2.0还支持获取上传文件的进度信息，因此我们可以根据进度信息可以实时的显示文件的上传进度。</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 需要注册 xhr.upload.onprogress = <span class="function"><span class="keyword">function</span>(<span class="params">e</span>)</span>&#123;&#125; 事件，用于监听文件上传的进度.注意：需要在send之前注册。</span><br><span class="line"><span class="number">2.</span> 上传的进度信息会存储事件对象e中</span><br><span class="line"><span class="number">3.</span> e.loaded表示已上传的大小   e.total表示整个文件的大小</span><br></pre></td></tr></table></figure>



<p>代码参考：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">xhr.upload.onprogress = <span class="function"><span class="keyword">function</span> (<span class="params">e</span>) </span>&#123;</span><br><span class="line">  </span><br><span class="line">  inner.style.width = (e.loaded/e.total*<span class="number">100</span>).toFixed(<span class="number">2</span>)+<span class="string">"%"</span>;</span><br><span class="line">  span.innerHTML = (e.loaded/e.total*<span class="number">100</span>).toFixed(<span class="number">2</span>)+<span class="string">"%"</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line">xhr.send(formData);</span><br></pre></td></tr></table></figure>

<p>如果上传文件超过8M，php会报错，需要进行设置，允许php上传大文件。</p>
<p><img src="/blog/2018/03/03/Ajax/ajax/%E5%89%8D%E7%AB%AF%E8%A7%86%E9%A2%91/38%E6%9C%9F%E5%B0%B1%E4%B8%9A%E7%8F%AD/ajax/01/01-%E6%95%99%E5%AD%A6%E8%B5%84%E6%96%99/image/php.png" alt></p>
<h2 id="跨域资源共享-CORS"><a href="#跨域资源共享-CORS" class="headerlink" title="跨域资源共享(CORS)"></a>跨域资源共享(CORS)</h2><h3 id="cors的使用"><a href="#cors的使用" class="headerlink" title="cors的使用"></a>cors的使用</h3><blockquote>
<p>新版本的XMLHttpRequest对象，可以向不同域名的服务器发出HTTP请求。这叫做<a href="http://en.wikipedia.org/wiki/Cross-Origin_Resource_Sharing" target="_blank" rel="noopener">“跨域资源共享”</a>（Cross-origin resource sharing，简称CORS）。</p>
</blockquote>
<p>跨域资源共享（CORS）的前提</p>
<ul>
<li>浏览器支持这个功能</li>
<li>服务器必须允许这种跨域。</li>
</ul>
<p>服务器允许跨域的代码：</p>
<figure class="highlight php"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//允许所有的域名访问这个接口</span></span><br><span class="line">header(<span class="string">"Access-Control-Allow-Origin:*"</span>);</span><br><span class="line"><span class="comment">//允许www.study.com这个域名访问这个接口</span></span><br><span class="line">header(<span class="string">"Access-Control-Allow-Origin:http://www.study.com"</span>);</span><br></pre></td></tr></table></figure>



<h3 id="CORS的具体流程（了解）"><a href="#CORS的具体流程（了解）" class="headerlink" title="CORS的具体流程（了解）"></a>CORS的具体流程（了解）</h3><ol>
<li>浏览器会根据<strong>同源策略</strong> 查看是否是跨域请求，如果同源，直接发送ajax请求。</li>
<li>如果非同源，说明是跨域请求，浏览器会自动发送一条请求（<strong>预检请求</strong> ），并不会携带数据，服务器接受到请求之后，会返回请求头信息，浏览器查看返回的响应头信息中是否设置了<code>header(&#39;Access-Control-Allow-Origin:请求源域名或者*&#39;);</code></li>
<li>如果没有设置，说明服务器不允许使用cors跨域，那么浏览器不会发送真正的ajax请求。</li>
<li>如果返回的响应头中设置了<code>header(&#39;Access-Control-Allow-Origin:请求源域名或者*&#39;);</code>,浏览器会跟请求头中的<code>Origin: http://www.study.com</code>进行对比，如果满足要求，则发送真正的ajax请求，否则不发送。</li>
<li>结论：<strong>跨域行为是浏览器行为，是浏览器阻止了ajax行为。服务器与服务器之间是不存在跨域的问题的</strong></li>
</ol>
<p>【案例：图灵机器人】</p>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://dttx123.gitee.io/2018/01/01/H5C3/H5C3/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
      <meta itemprop="name" content="大春哥">
      <meta itemprop="description" content="IT">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Starry Night">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blog/2018/01/01/H5C3/H5C3/" class="post-title-link" itemprop="url">H5C3</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2018-01-01 00:00:00" itemprop="dateCreated datePublished" datetime="2018-01-01T00:00:00+08:00">2018-01-01</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-05-13 20:42:07" itemprop="dateModified" datetime="2020-05-13T20:42:07+08:00">2020-05-13</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/H5C3/" itemprop="url" rel="index"><span itemprop="name">H5C3</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h2 id="HTML5的发展-了解"><a href="#HTML5的发展-了解" class="headerlink" title="HTML5的发展(了解)"></a>HTML5的发展(了解)</h2><blockquote>
<p>1-HTML  的历史：<br>1993 年 HTML 首次以因特网草案的形式发布，然后经历了 2.0、3.2 和 4.0，直到 1999 年的 HTML 4.01 版本稳定下来。 后来逐渐被更加严格的 XHTML 取代。</p>
</blockquote>
          <!--noindex-->
            <div class="post-button">
              <a class="btn" href="/blog/2018/01/01/H5C3/H5C3/#more" rel="contents">
                阅读全文 &raquo;
              </a>
            </div>
          <!--/noindex-->
        
      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://dttx123.gitee.io/2018/01/01/H5C3/H5-API/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
      <meta itemprop="name" content="大春哥">
      <meta itemprop="description" content="IT">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Starry Night">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blog/2018/01/01/H5C3/H5-API/" class="post-title-link" itemprop="url">H5的API</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2018-01-01 00:00:00" itemprop="dateCreated datePublished" datetime="2018-01-01T00:00:00+08:00">2018-01-01</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-05-13 10:36:47" itemprop="dateModified" datetime="2020-05-13T10:36:47+08:00">2020-05-13</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/H5C3/" itemprop="url" rel="index"><span itemprop="name">H5C3</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <p>#HTML5-API</p>
<h1 id="网络状态"><a href="#网络状态" class="headerlink" title="网络状态"></a>网络状态</h1><blockquote>
<p>在移动端，我们经常需要检测设置是在线还是离线，HTML5为此定义了一个navigator.onLine属性，这个属性用于检测设备是否联网。<strong><em>navigator.onLine</em></strong> 在不同浏览器中有细微的差别。</p>
</blockquote>
<h2 id="网络状态-1"><a href="#网络状态-1" class="headerlink" title="网络状态"></a>网络状态</h2><p>【01.网络状态.html】</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">navigator.onLine返回用户当前的网络状况，是一个布尔值</span><br><span class="line"><span class="number">1.</span> 如果浏览器连不上网(包括局域网)，就是离线状态，也就是脱机状态，会返回<span class="literal">false</span></span><br><span class="line"><span class="number">2.</span> 否则就是在线状态，返回<span class="literal">true</span></span><br></pre></td></tr></table></figure>

<p><strong><em>注意：返回true不一定就是说一定能访问互联网，因为有可能连接的是局域网。但是返回false则表示一定连不上网。</em></strong></p>
<h2 id="监听网络变化"><a href="#监听网络变化" class="headerlink" title="监听网络变化"></a>监听网络变化</h2><p>【02-判断网络状态.html】</p>
<blockquote>
<p>为了更好的确定网络是否连接，HTML5还定义了两个事件，用于监听网络状态的变化。</p>
</blockquote>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//网络连接时会被调用</span></span><br><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">"online"</span>, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    alert(<span class="string">"online"</span>);</span><br><span class="line">&#125;);</span><br><span class="line"><span class="comment">//网络断开时会被调用</span></span><br><span class="line"><span class="built_in">window</span>.addEventListener(<span class="string">"offline"</span>, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    alert(<span class="string">"offline"</span>);</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>



<h1 id="地理位置"><a href="#地理位置" class="headerlink" title="地理位置"></a>地理位置</h1><blockquote>
<p>在HTML规范中，增加了获取用户地理信息的API，这样使得我们可以基于用户位置开发互联网应用，即基于位置服务LBS(Location Base Service)</p>
</blockquote>
<h2 id="隐私"><a href="#隐私" class="headerlink" title="隐私"></a>隐私</h2><p>HTML5规范提供了一套保护用户隐私的机制。必须先得到用户明确许可，才能获取用户的位置信息。<strong><em>在获取地理位置之前，会询问用户，只有在获得许可之后，才能获取到用户的位置信息。</em></strong> </p>
<h2 id="相关的方法"><a href="#相关的方法" class="headerlink" title="相关的方法"></a>相关的方法</h2><p>【03-获取地理位置.html】</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//successCallback:获取成功后会调用,并返回一个position对象，里面包含了地理位置信息</span></span><br><span class="line"><span class="comment">//获取失败了会调用，并返回error对象，里面包含了错误信息。</span></span><br><span class="line"><span class="comment">//获取当前的地理位置信息</span></span><br><span class="line">navigator.geolocation.getCurrentPosition(successCallback, errorCallback)</span><br><span class="line"><span class="comment">//重复的获取当前的地理位置信息</span></span><br><span class="line">navigator.geolocation.watchPosition(successCallback, errorCallback)</span><br></pre></td></tr></table></figure>
<p>实例：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">navigator.geolocation.getCurrentPosition(<span class="function"><span class="keyword">function</span>(<span class="params">position</span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 定位成功会调用该方法</span></span><br><span class="line">    <span class="comment">// position.coords.latitude 纬度</span></span><br><span class="line">    <span class="comment">// position.coords.longitude 经度</span></span><br><span class="line">    <span class="comment">// position.coords.accuracy 精度</span></span><br><span class="line">    <span class="comment">// position.coords.altitude 海拔高度</span></span><br><span class="line">&#125;, <span class="function"><span class="keyword">function</span>(<span class="params">error</span>)</span>&#123;</span><br><span class="line">    <span class="comment">// 定位失败会调用该方法</span></span><br><span class="line">    <span class="comment">// error 是错误信息</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>

<p><strong><em>在iOS 10中，苹果对webkit定位权限进行了修改，所有定位请求的页面必须是https协议的。</em></strong> </p>
<h2 id="百度地图"><a href="#百度地图" class="headerlink" title="百度地图"></a>百度地图</h2><blockquote>
<p>仅仅获取到经纬度对于用户来说意义并不大，因为用户也不知道经度和纬度表示的是地球上的哪一个地方，因为我们可以结合百度地图，准确的将用户的位置显示出来。</p>
</blockquote>
<p>百度地图官网：<a href="http://lbsyun.baidu.com/" target="_blank" rel="noopener">http://lbsyun.baidu.com/</a></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 在开发中，找到javascript API</span><br><span class="line"><span class="number">2.</span> 直接查看示例demo</span><br><span class="line"><span class="number">3.</span> 复制相应的代码，替换掉秘钥就行，秘钥只需创建一个新的应用就可以了。</span><br></pre></td></tr></table></figure>



<h1 id="web存储"><a href="#web存储" class="headerlink" title="web存储"></a>web存储</h1><blockquote>
<p>在代码执行的时候，数据都是存储在内存中的，当页面关闭或者浏览器关闭的时候，内存就被释放掉了。数据只有存储在硬盘上，才不会被释放。</p>
</blockquote>
<p>【01-web存储初体验.html】</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//存储在内存中，会被释放</span></span><br><span class="line">    <span class="keyword">var</span> str = <span class="string">"hello world"</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(str);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//存储在硬盘上，不会被释放</span></span><br><span class="line">    localStorage.setItem(<span class="string">"name"</span>, <span class="string">"张三"</span>);</span><br><span class="line">    <span class="built_in">console</span>.log(localStorage.getItem(<span class="string">"name"</span>));</span><br></pre></td></tr></table></figure>



<h2 id="cookie-了解"><a href="#cookie-了解" class="headerlink" title="cookie(了解)"></a>cookie(了解)</h2><blockquote>
<p>传统方式，我们以document.cookie进行存储，但是存储起来特别麻烦，并且，存储大小只有4k，常用来做自动登录，即存储用户的账号和密码信息。每次请求都会带上cookie</p>
</blockquote>
<p>【02-cookie存储.html】<br>cookie是以字符串形式存在的，这个字符串有固定的格式：key=value;key1=value1;</p>
<p>在获取cookie内容时，一般需要通过正则或者字符串的方法进行处理，转换成对象，最终得到数据。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="built_in">document</span>.cookie = <span class="string">"name=zhangsan"</span>;</span><br><span class="line"><span class="built_in">document</span>.cookie = <span class="string">"age=18"</span>;</span><br><span class="line"><span class="built_in">document</span>.cookie = <span class="string">"sex=23"</span>;</span><br><span class="line"></span><br><span class="line"><span class="comment">//读取cookie</span></span><br><span class="line"><span class="keyword">var</span> result = <span class="built_in">document</span>.cookie;</span><br><span class="line"><span class="built_in">console</span>.log(result);</span><br></pre></td></tr></table></figure>

<p>使用原生js操作cookie太过麻烦，尤其是cookie的获取和删除操作，使用jquery.cookie插件，能够简化我们的操作。</p>
<p>【03-cookie存储（jquery插件）.html】</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//设置cookie</span></span><br><span class="line">$.cookie(<span class="string">"name"</span>, <span class="string">"zs"</span>);</span><br><span class="line"><span class="comment">//获取cookie</span></span><br><span class="line"><span class="built_in">console</span>.log($.cookie(<span class="string">"name"</span>));</span><br><span class="line"><span class="comment">//删除cookie</span></span><br><span class="line">$.removeCookie(<span class="string">"name"</span>);</span><br></pre></td></tr></table></figure>
<p><strong>使用cookie：操作太麻烦，最多只能存储4k ,每次请求都会带上cookie，所以用户名和密码、还有sessionID会存储在cookie中</strong>   </p>
<h2 id="sessionStorage与localStorage"><a href="#sessionStorage与localStorage" class="headerlink" title="sessionStorage与localStorage"></a>sessionStorage与localStorage</h2><blockquote>
<p>HTML5规范提出了解决方案，使用sessionStorage和localStorage存储数据。设置、读取、删除操作很方便</p>
</blockquote>
<p>window.sessionStorage的特点</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 声明周期为关闭浏览器窗口</span><br><span class="line"><span class="number">2.</span> 不能在多个窗口下共享数据。</span><br><span class="line"><span class="number">3.</span> 大小为<span class="number">5</span>M</span><br></pre></td></tr></table></figure>

<p>window.localStorage的特点</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="number">1.</span> 永久生效，除非手动删除</span><br><span class="line"><span class="number">2.</span> 可以多个窗口共享</span><br><span class="line"><span class="number">3.</span> 大小为<span class="number">20</span>M</span><br></pre></td></tr></table></figure>

<p>window.sessionStorage与window.localStorage的方法</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">setItem(key, value) <span class="comment">//设置存储内容</span></span><br><span class="line">getItem(key) <span class="comment">//读取存储内容</span></span><br><span class="line">removeItem(key) <span class="comment">//删除键值为key的存储内容</span></span><br><span class="line">clear() <span class="comment">//清空所有存储内容</span></span><br><span class="line">key(n) <span class="comment">//以索引值来获取存储内容</span></span><br></pre></td></tr></table></figure>

<p>【04-sessionStorage与localStorage的用法.html】</p>
<p>【05-案例-换肤效果.html】</p>
<p><strong>面试题：请描述一下cookies，sessionStorage和localStorage的区别？</strong></p>
<h1 id="自定义播放器"><a href="#自定义播放器" class="headerlink" title="自定义播放器"></a>自定义播放器</h1><p>全屏切换API：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">video.requestFullScreen()</span><br></pre></td></tr></table></figure>
<p>方法：load()、play()、pause()<br>属性：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">currentTime:当前时间</span><br><span class="line">duration：总长时间</span><br><span class="line">timeupdate:播放进度更改时触发</span><br><span class="line">volume：控制音量</span><br></pre></td></tr></table></figure>


<p>参考文档<br><a href="http://www.w3school.com.cn/tags/html_ref_audio_video_dom.asp" target="_blank" rel="noopener">http://www.w3school.com.cn/tags/html_ref_audio_video_dom.asp</a></p>
<p><strong><em>主要目的是练习一下video的属性和方法，还有之前我们学过的js</em></strong> </p>
<p>推荐网站：<a href="https://www.awesomes.cn/" target="_blank" rel="noopener">https://www.awesomes.cn/</a></p>
<h1 id="文件读取"><a href="#文件读取" class="headerlink" title="文件读取"></a>文件读取</h1><blockquote>
<p>通过FileReader对象我们可以读取本地存储的文件，可以使用 File 对象来指定所要读取的文件或数据。其中File对象可以是来自用户在一个<code>&lt;input&gt;</code>元素上选择文件后返回的FileList 对象，也可以来自由拖放操作生成的  DataTransfer</p>
</blockquote>
<h2 id="files"><a href="#files" class="headerlink" title="files"></a>files</h2><p>对于file类型的input框，在这个DOM对象中，存在一个files属性，这个属性是FileList对象，是一个伪数组，里面存储着上传的所有文件，当input框指定了multiple属性之后，就可以上传多个文件了。</p>
<p>也就是说，通过files这个属性，我们就可以获取到所有上传的文件。</p>
<h2 id="file对象"><a href="#file对象" class="headerlink" title="file对象"></a>file对象</h2><p>File对象中包含了文件的最后修改时间、文件名、文件类型等信息。</p>
<h2 id="FileReader对象"><a href="#FileReader对象" class="headerlink" title="FileReader对象"></a>FileReader对象</h2><p>FileReader是一个HTML5新增的对象，用于读取文件。</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//创建一个fileReader对象</span></span><br><span class="line"><span class="keyword">var</span> fr = <span class="keyword">new</span> FileReader;</span><br><span class="line"><span class="comment">//读取文件的两个方法</span></span><br><span class="line"><span class="comment">//readAsText() 以文本的方式读取文件 ,文本文件</span></span><br><span class="line"><span class="comment">//readAsDataURL() 以DataURL形式读取文件，图片，视频</span></span><br><span class="line"><span class="comment">//文件读取完成事件：</span></span><br><span class="line">fr.onload = <span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;&#125;</span><br><span class="line"><span class="comment">//当文件读取完成，可以通过result属性获取结果</span></span><br><span class="line">fr.result</span><br></pre></td></tr></table></figure>
<p>参考资料：<br><a href="https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader#toc" target="_blank" rel="noopener">https://developer.mozilla.org/zh-CN/docs/Web/API/FileReader#toc</a></p>
<p>案例：</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">var</span> file = <span class="built_in">document</span>.getElementById(<span class="string">"file"</span>);</span><br><span class="line">    <span class="keyword">var</span> box = <span class="built_in">document</span>.getElementById(<span class="string">"box"</span>);</span><br><span class="line"></span><br><span class="line">    file.addEventListener(<span class="string">"change"</span>, <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">        <span class="built_in">console</span>.dir(file);</span><br><span class="line">        </span><br><span class="line">        <span class="comment">//files:里面存储了所有上传的文件</span></span><br><span class="line">        <span class="comment">//这个data就是我们上传的那个文件</span></span><br><span class="line">        <span class="keyword">var</span> data = file.files[<span class="number">0</span>]</span><br><span class="line">      </span><br><span class="line">        <span class="comment">//1. 创建一个文件读取器</span></span><br><span class="line">        <span class="keyword">var</span> fr = <span class="keyword">new</span> FileReader();</span><br><span class="line"></span><br><span class="line">        <span class="comment">//2. 让文件读取器读取整个文件</span></span><br><span class="line">        fr.readAsDataURL(data);</span><br><span class="line"></span><br><span class="line">        <span class="comment">//3. 等待文件读取完</span></span><br><span class="line">        <span class="comment">//onload：文件读取完成后，就会触发</span></span><br><span class="line">        fr.onload = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">            <span class="keyword">var</span> img = <span class="built_in">document</span>.createElement(<span class="string">"img"</span>);</span><br><span class="line">            img.src = fr.result;</span><br><span class="line">            box.innerHTML = <span class="string">""</span>;</span><br><span class="line">            box.appendChild(img);</span><br><span class="line">        &#125;</span><br><span class="line">    &#125;);</span><br></pre></td></tr></table></figure>



<h1 id="拖拽"><a href="#拖拽" class="headerlink" title="拖拽"></a>拖拽</h1><p>在HTML5的规范中，我们可以通过为元素增加draggable=”true”来设置此元素是否可以进行拖拽操作，其中图片、链接默认是开启的。</p>
<h2 id="拖拽元素"><a href="#拖拽元素" class="headerlink" title="拖拽元素"></a>拖拽元素</h2><p>页面中设置了draggable=”true”属性的元素，其中<code>&lt;img&gt;</code>、<code>&lt;a&gt;</code>标签默认是可以被拖拽的</p>
<h2 id="目标元素"><a href="#目标元素" class="headerlink" title="目标元素"></a>目标元素</h2><p>页面中任何一个元素都可以成为目标元素</p>
<h2 id="事件监听"><a href="#事件监听" class="headerlink" title="事件监听"></a>事件监听</h2><p>根据元素类型不同，需要设置不同的事件监听</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//1、拖拽元素</span></span><br><span class="line">ondrag 应用于拖拽元素，整个拖拽过程都会调用</span><br><span class="line">ondragstart应用于拖拽元素，当拖拽开始时调用</span><br><span class="line">ondragend应用于拖拽元素，当拖拽结束时调用</span><br><span class="line"><span class="comment">//2、目标元素</span></span><br><span class="line">ondragover应用于目标元素，当停留在目标元素上时调用</span><br><span class="line">ondrop应用于目标元素，当在目标元素上松开鼠标时调用(浏览器默认不让拖拽，需要阻止的默认行为。)</span><br></pre></td></tr></table></figure>

      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://dttx123.gitee.io/2017/11/11/javaScript/js%E5%B8%B8%E7%94%A8%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E5%B0%81%E8%A3%85/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
      <meta itemprop="name" content="大春哥">
      <meta itemprop="description" content="IT">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Starry Night">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blog/2017/11/11/javaScript/js%E5%B8%B8%E7%94%A8%E6%95%B0%E6%8D%AE%E7%BB%93%E6%9E%84%E5%B0%81%E8%A3%85/" class="post-title-link" itemprop="url">常用数据结构</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-11-11 00:00:00" itemprop="dateCreated datePublished" datetime="2017-11-11T00:00:00+08:00">2017-11-11</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-07-06 23:11:27" itemprop="dateModified" datetime="2020-07-06T23:11:27+08:00">2020-07-06</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/js%E5%9F%BA%E7%A1%80/" itemprop="url" rel="index"><span itemprop="name">js基础</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="js-常用数据结构的封装（待优化）"><a href="#js-常用数据结构的封装（待优化）" class="headerlink" title="js 常用数据结构的封装（待优化）"></a>js 常用数据结构的封装（待优化）</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br><span class="line">203</span><br><span class="line">204</span><br><span class="line">205</span><br><span class="line">206</span><br><span class="line">207</span><br><span class="line">208</span><br><span class="line">209</span><br><span class="line">210</span><br><span class="line">211</span><br><span class="line">212</span><br><span class="line">213</span><br><span class="line">214</span><br><span class="line">215</span><br><span class="line">216</span><br><span class="line">217</span><br><span class="line">218</span><br><span class="line">219</span><br><span class="line">220</span><br><span class="line">221</span><br><span class="line">222</span><br><span class="line">223</span><br><span class="line">224</span><br><span class="line">225</span><br><span class="line">226</span><br><span class="line">227</span><br><span class="line">228</span><br><span class="line">229</span><br><span class="line">230</span><br><span class="line">231</span><br><span class="line">232</span><br><span class="line">233</span><br><span class="line">234</span><br><span class="line">235</span><br><span class="line">236</span><br><span class="line">237</span><br><span class="line">238</span><br><span class="line">239</span><br><span class="line">240</span><br><span class="line">241</span><br><span class="line">242</span><br><span class="line">243</span><br><span class="line">244</span><br><span class="line">245</span><br><span class="line">246</span><br><span class="line">247</span><br><span class="line">248</span><br><span class="line">249</span><br><span class="line">250</span><br><span class="line">251</span><br><span class="line">252</span><br><span class="line">253</span><br><span class="line">254</span><br><span class="line">255</span><br><span class="line">256</span><br><span class="line">257</span><br><span class="line">258</span><br><span class="line">259</span><br><span class="line">260</span><br><span class="line">261</span><br><span class="line">262</span><br><span class="line">263</span><br><span class="line">264</span><br><span class="line">265</span><br><span class="line">266</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 栈</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Stack</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> items = []</span><br><span class="line">  <span class="keyword">this</span>.push = <span class="function"><span class="keyword">function</span> (<span class="params">element</span>) </span>&#123;</span><br><span class="line">    items.push(element)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.pop = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> items.pop()</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.peek = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> items[items.length - <span class="number">1</span>]</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.isEmpty = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> items.length == <span class="number">0</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.size = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> items.length</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.clear = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    items = []</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.print = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(items.toString())</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 队列</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">Queue</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> items = []</span><br><span class="line">  <span class="keyword">this</span>.enqueue = <span class="function"><span class="keyword">function</span> (<span class="params">element</span>) </span>&#123;</span><br><span class="line">    items.push(element)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.dequeue = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> items.shift()</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.front = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> items[<span class="number">0</span>]</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.isEmpty = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> items.length == <span class="number">0</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.clear = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    items = []</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.size = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> items.length</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">this</span>.print = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="built_in">console</span>.log(items.toString())</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 链表</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">LinkedList</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> Node = <span class="function"><span class="keyword">function</span> (<span class="params">element</span>) </span>&#123;</span><br><span class="line">    <span class="comment">// &#123;1&#125;</span></span><br><span class="line">    <span class="keyword">this</span>.element = element</span><br><span class="line">    <span class="keyword">this</span>.next = <span class="literal">null</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">var</span> length = <span class="number">0</span> <span class="comment">// &#123;2&#125;</span></span><br><span class="line">  <span class="keyword">var</span> head = <span class="literal">null</span> <span class="comment">// &#123;3&#125;</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">this</span>.append = <span class="function"><span class="keyword">function</span> (<span class="params">element</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> node = <span class="keyword">new</span> Node(element), <span class="comment">//&#123;1&#125;</span></span><br><span class="line">      current <span class="comment">//&#123;2&#125;</span></span><br><span class="line">    <span class="keyword">if</span> (head === <span class="literal">null</span>) &#123;</span><br><span class="line">      <span class="comment">//列表中第一个节点 //&#123;3&#125;</span></span><br><span class="line">      head = node</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      current = head <span class="comment">//&#123;4&#125;</span></span><br><span class="line">      <span class="comment">//循环列表，直到找到最后一项</span></span><br><span class="line">      <span class="keyword">while</span> (current.next) &#123;</span><br><span class="line">        current = current.next</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="comment">//找到最后一项，将其next赋为node，建立链接</span></span><br><span class="line">      current.next = node <span class="comment">//&#123;5&#125;</span></span><br><span class="line">    &#125;</span><br><span class="line">    length++ <span class="comment">//更新列表的长度 //&#123;6&#125;</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">this</span>.insert = <span class="function"><span class="keyword">function</span> (<span class="params">position, element</span>) </span>&#123;</span><br><span class="line">    <span class="comment">//检查越界值</span></span><br><span class="line">    <span class="keyword">if</span> (position &gt;= <span class="number">0</span> &amp;&amp; position &lt;= length) &#123;</span><br><span class="line">      <span class="comment">//&#123;1&#125;</span></span><br><span class="line">      <span class="keyword">var</span> node = <span class="keyword">new</span> Node(element),</span><br><span class="line">        current = head,</span><br><span class="line">        previous,</span><br><span class="line">        index = <span class="number">0</span></span><br><span class="line">      <span class="keyword">if</span> (position === <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="comment">//在第一个位置添加</span></span><br><span class="line">        node.next = current <span class="comment">//&#123;2&#125;</span></span><br><span class="line">        head = node</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">while</span> (index++ &lt; position) &#123;</span><br><span class="line">          <span class="comment">//&#123;3&#125;</span></span><br><span class="line">          previous = current</span><br><span class="line">          current = current.next</span><br><span class="line">        &#125;</span><br><span class="line">        node.next = current <span class="comment">//&#123;4&#125;</span></span><br><span class="line">        previous.next = node <span class="comment">//&#123;5&#125;</span></span><br><span class="line">      &#125;</span><br><span class="line">      length++ <span class="comment">//更新列表的长度</span></span><br><span class="line">      <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">false</span> <span class="comment">//&#123;6&#125;</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">this</span>.removeAt = <span class="function"><span class="keyword">function</span> (<span class="params">position</span>) </span>&#123;</span><br><span class="line">    <span class="comment">//检查越界值</span></span><br><span class="line">    <span class="keyword">if</span> (position &gt; <span class="number">-1</span> &amp;&amp; position &lt; length) &#123;</span><br><span class="line">      <span class="comment">// &#123;1&#125;</span></span><br><span class="line">      <span class="keyword">var</span> current = head, <span class="comment">// &#123;2&#125;</span></span><br><span class="line">        previous, <span class="comment">// &#123;3&#125;</span></span><br><span class="line">        index = <span class="number">0</span> <span class="comment">// &#123;4&#125;</span></span><br><span class="line">      <span class="comment">//移除第一项</span></span><br><span class="line">      <span class="keyword">if</span> (position === <span class="number">0</span>) &#123;</span><br><span class="line">        <span class="comment">// &#123;5&#125;</span></span><br><span class="line">        head = current.next</span><br><span class="line">      &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">        <span class="keyword">while</span> (index++ &lt; position) &#123;</span><br><span class="line">          <span class="comment">// &#123;6&#125;</span></span><br><span class="line">          previous = current <span class="comment">// &#123;7&#125;</span></span><br><span class="line">          current = current.next <span class="comment">// &#123;8&#125;</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="comment">//将previous与current的下一项链接起来：跳过current，从而移除它</span></span><br><span class="line">        previous.next = current.next <span class="comment">// &#123;9&#125;</span></span><br><span class="line">      &#125;</span><br><span class="line">      length-- <span class="comment">// &#123;10&#125;</span></span><br><span class="line">      <span class="keyword">return</span> current.element</span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">null</span> <span class="comment">// &#123;11&#125;</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">this</span>.remove = <span class="function"><span class="keyword">function</span> (<span class="params">element</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> index = <span class="keyword">this</span>.indexOf(element)</span><br><span class="line">    <span class="keyword">return</span> <span class="keyword">this</span>.removeAt(index)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">this</span>.indexOf = <span class="function"><span class="keyword">function</span> (<span class="params">element</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> current = head, <span class="comment">//&#123;1&#125;</span></span><br><span class="line">      index = <span class="number">-1</span></span><br><span class="line">    <span class="keyword">while</span> (current) &#123;</span><br><span class="line">      <span class="comment">//&#123;2&#125;</span></span><br><span class="line">      <span class="keyword">if</span> (element === current.element) &#123;</span><br><span class="line">        <span class="keyword">return</span> index <span class="comment">//&#123;3&#125;</span></span><br><span class="line">      &#125;</span><br><span class="line">      index++ <span class="comment">//&#123;4&#125;</span></span><br><span class="line">      current = current.next <span class="comment">//&#123;5&#125;</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="number">-1</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">this</span>.isEmpty = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> length === <span class="number">0</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">this</span>.size = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> length</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">this</span>.toString = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> current = head, <span class="comment">//&#123;1&#125;</span></span><br><span class="line">      string = <span class="string">''</span> <span class="comment">//&#123;2&#125;</span></span><br><span class="line">    <span class="keyword">while</span> (current) &#123;</span><br><span class="line">      <span class="comment">//&#123;3&#125;</span></span><br><span class="line">      string = current.element <span class="comment">//&#123;4&#125;</span></span><br><span class="line">      current = current.next <span class="comment">//&#123;5&#125;</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> string <span class="comment">//&#123;6&#125;</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.print = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;&#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">this</span>.getHead = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> head</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br><span class="line"><span class="comment">// 集合</span></span><br><span class="line"><span class="function"><span class="keyword">function</span> <span class="title">List</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">  <span class="keyword">var</span> items = &#123;&#125;</span><br><span class="line">  <span class="keyword">this</span>.has = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> items.hasOwnProperty(value)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">this</span>.add = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (!<span class="keyword">this</span>.has(value)) &#123;</span><br><span class="line">      items[value] = value <span class="comment">//&#123;1&#125;</span></span><br><span class="line">      <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">this</span>.remove = <span class="function"><span class="keyword">function</span> (<span class="params">value</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.has(value)) &#123;</span><br><span class="line">      <span class="keyword">delete</span> items[value] <span class="comment">//&#123;2&#125;</span></span><br><span class="line">      <span class="keyword">return</span> <span class="literal">true</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">this</span>.clear = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    items = &#123;&#125; <span class="comment">// &#123;3&#125;</span></span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">this</span>.size = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">Object</span>.keys(items).length <span class="comment">//&#123;4&#125;</span></span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">this</span>.values = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">return</span> <span class="built_in">Object</span>.keys(items)</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">this</span>.valuesLegacy = <span class="function"><span class="keyword">function</span> (<span class="params"></span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> keys = []</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> key <span class="keyword">in</span> items) &#123;</span><br><span class="line">      <span class="comment">//&#123;7&#125;</span></span><br><span class="line">      keys.push(key) <span class="comment">//&#123;8&#125;</span></span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> keys</span><br><span class="line">  &#125;</span><br><span class="line"></span><br><span class="line">  <span class="comment">// 交集</span></span><br><span class="line">  <span class="keyword">this</span>.intersection = <span class="function"><span class="keyword">function</span> (<span class="params">otherSet</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> intersectionSet = <span class="keyword">new</span> <span class="built_in">Set</span>() <span class="comment">//&#123;1&#125;</span></span><br><span class="line">    <span class="keyword">var</span> values = <span class="keyword">this</span>.values()</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; values.length; i++) &#123;</span><br><span class="line">      <span class="comment">//&#123;2&#125;</span></span><br><span class="line">      <span class="keyword">if</span> (otherSet.has(values[i])) &#123;</span><br><span class="line">        <span class="comment">//&#123;3&#125;</span></span><br><span class="line">        intersectionSet.add(values[i]) <span class="comment">//&#123;4&#125;</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> intersectionSet</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 差集</span></span><br><span class="line">  <span class="keyword">this</span>.difference = <span class="function"><span class="keyword">function</span> (<span class="params">otherSet</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> differenceSet = <span class="keyword">new</span> <span class="built_in">Set</span>() <span class="comment">//&#123;1&#125;</span></span><br><span class="line">    <span class="keyword">var</span> values = <span class="keyword">this</span>.values()</span><br><span class="line">    <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; values.length; i++) &#123;</span><br><span class="line">      <span class="comment">//&#123;2&#125;</span></span><br><span class="line">      <span class="keyword">if</span> (!otherSet.has(values[i])) &#123;</span><br><span class="line">        <span class="comment">//&#123;3&#125;</span></span><br><span class="line"></span><br><span class="line">        differenceSet.add(values[i]) <span class="comment">//&#123;4&#125;</span></span><br><span class="line">      &#125;</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> differenceSet</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="comment">// 子集</span></span><br><span class="line">  <span class="keyword">this</span>.subset = <span class="function"><span class="keyword">function</span> (<span class="params">otherSet</span>) </span>&#123;</span><br><span class="line">    <span class="keyword">if</span> (<span class="keyword">this</span>.size() &gt; otherSet.size()) &#123;</span><br><span class="line">      <span class="comment">//&#123;1&#125;</span></span><br><span class="line">      <span class="keyword">return</span> <span class="literal">false</span></span><br><span class="line">    &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">      <span class="keyword">var</span> values = <span class="keyword">this</span>.values()</span><br><span class="line">      <span class="keyword">for</span> (<span class="keyword">var</span> i = <span class="number">0</span>; i &lt; values.length; i++) &#123;</span><br><span class="line">        <span class="comment">//&#123;2&#125;</span></span><br><span class="line">        <span class="keyword">if</span> (!otherSet.has(values[i])) &#123;</span><br><span class="line">          <span class="comment">//&#123;3&#125;</span></span><br><span class="line">          <span class="keyword">return</span> <span class="literal">false</span> <span class="comment">//&#123;4&#125;</span></span><br><span class="line">        &#125;</span><br><span class="line">      &#125;</span><br><span class="line">      <span class="keyword">return</span> <span class="literal">true</span> <span class="comment">//&#123;5&#125;</span></span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>


      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  

      
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://dttx123.gitee.io/2017/09/15/javaScript/%E7%9B%91%E5%90%AC%E9%A1%B5%E9%9D%A2%E5%85%A8%E5%B1%80%E9%94%99%E8%AF%AF%E4%BF%A1%E6%81%AF/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/blog/images/avatar.jpg">
      <meta itemprop="name" content="大春哥">
      <meta itemprop="description" content="IT">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Starry Night">
    </span>
      <header class="post-header">
        <h2 class="post-title" itemprop="name headline">
          
            <a href="/blog/2017/09/15/javaScript/%E7%9B%91%E5%90%AC%E9%A1%B5%E9%9D%A2%E5%85%A8%E5%B1%80%E9%94%99%E8%AF%AF%E4%BF%A1%E6%81%AF/" class="post-title-link" itemprop="url">监听页面的全局错误</a>
        </h2>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">发表于</span>

              <time title="创建时间：2017-09-15 00:00:00" itemprop="dateCreated datePublished" datetime="2017-09-15T00:00:00+08:00">2017-09-15</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">更新于</span>
                <time title="修改时间：2020-07-06 23:10:55" itemprop="dateModified" datetime="2020-07-06T23:10:55+08:00">2020-07-06</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">分类于</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/blog/categories/js%E5%9F%BA%E7%A1%80/" itemprop="url" rel="index"><span itemprop="name">js基础</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
          <h1 id="监听页面的全局错误"><a href="#监听页面的全局错误" class="headerlink" title="监听页面的全局错误"></a>监听页面的全局错误</h1><figure class="highlight js"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="built_in">window</span>.onerror = <span class="function"><span class="keyword">function</span> (<span class="params"></span></span></span><br><span class="line"><span class="function"><span class="params">    errorMessage,</span></span></span><br><span class="line"><span class="function"><span class="params">    scriptURI,</span></span></span><br><span class="line"><span class="function"><span class="params">    lineNumber,</span></span></span><br><span class="line"><span class="function"><span class="params">    columnNumber,</span></span></span><br><span class="line"><span class="function"><span class="params">    errorObj</span></span></span><br><span class="line"><span class="function"><span class="params">  </span>) </span>&#123;</span><br><span class="line">    <span class="keyword">var</span> info =</span><br><span class="line">      <span class="string">"错误信息："</span> +</span><br><span class="line">      errorMessage +</span><br><span class="line">      <span class="string">"\n"</span> +</span><br><span class="line">      <span class="string">"出错文件："</span> +</span><br><span class="line">      scriptURI +</span><br><span class="line">      <span class="string">"\n"</span> +</span><br><span class="line">      <span class="string">"出错行号："</span> +</span><br><span class="line">      lineNumber +</span><br><span class="line">      <span class="string">"\n"</span> +</span><br><span class="line">      <span class="string">"出错列号："</span> +</span><br><span class="line">      columnNumber +</span><br><span class="line">      <span class="string">"\n"</span> +</span><br><span class="line">      <span class="string">"错误详情："</span> +</span><br><span class="line">      errorObj +</span><br><span class="line">      <span class="string">"\n"</span>;</span><br><span class="line">    <span class="built_in">console</span>.log(info);</span><br><span class="line">    <span class="comment">// 发送给后台....</span></span><br><span class="line">  &#125;;</span><br></pre></td></tr></table></figure>


      
    </div>

    
    
    
      <footer class="post-footer">
        <div class="post-eof"></div>
      </footer>
  </article>
  
  
  


  
  <nav class="pagination">
    <a class="extend prev" rel="prev" href="/blog/"><i class="fa fa-angle-left" aria-label="上一页"></i></a><a class="page-number" href="/blog/">1</a><span class="page-number current">2</span><a class="page-number" href="/blog/page/3/">3</a><a class="page-number" href="/blog/page/4/">4</a><a class="extend next" rel="next" href="/blog/page/3/"><i class="fa fa-angle-right" aria-label="下一页"></i></a>
  </nav>



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="大春哥"
      src="/blog/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">大春哥</p>
  <div class="site-description" itemprop="description">IT</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/blog/archives/">
        
          <span class="site-state-item-count">35</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/blog/categories/">
          
        <span class="site-state-item-count">11</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/blog/tags/">
          
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2020</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">大春哥</span>
</div>

        








      </div>
    </footer>
  </div>

  
  <script src="/blog/lib/anime.min.js"></script>
  <script src="/blog/lib/velocity/velocity.min.js"></script>
  <script src="/blog/lib/velocity/velocity.ui.min.js"></script>

<script src="/blog/js/utils.js"></script>

<script src="/blog/js/motion.js"></script>


<script src="/blog/js/schemes/pisces.js"></script>


<script src="/blog/js/next-boot.js"></script>




  




  
<script src="/blog/js/local-search.js"></script>













  

  

</body>
</html>
